Commit 015d4257 authored by kang.nie@inzymeits.com's avatar kang.nie@inzymeits.com
Browse files

初始化代码

parent bd38ff8b
Pipeline #3108 failed with stages
in 0 seconds
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.rnr.fp.constants.BizTypeEnum;
import com.cusc.nirvana.user.rnr.fp.dto.FpRnrSmsInfoDTO;
import com.cusc.nirvana.user.rnr.fp.dto.MessageBizTypeEnum;
import com.cusc.nirvana.user.rnr.fp.dto.SmsRequestDTO;
import com.cusc.nirvana.user.rnr.fp.dto.SmsResponseDTO;
import com.cusc.nirvana.user.rnr.fp.service.EnterpriseUnBindService;
import com.cusc.nirvana.user.rnr.fp.service.IFpRnrSmsInfoService;
import com.cusc.nirvana.user.rnr.fp.service.ShortMessageCheckService;
import com.cusc.nirvana.user.rnr.mg.client.ChangeOrUnbindIccidsClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrRelationClient;
import com.cusc.nirvana.user.rnr.mg.dto.RnrOrderDTO;
import com.cusc.nirvana.user.rnr.mg.dto.RnrRelationDTO;
import com.cusc.nirvana.user.util.CuscStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @className: EnterpriseUnBindServiceImpl
* @description: 企业解绑
* @author: jk
* @date: 2022/6/17 14:46
* @version: 1.0
**/
@Service
@Slf4j
public class EnterpriseUnBindServiceImpl implements EnterpriseUnBindService {
@Resource
private MgRnrRelationClient mgRnrRelationClient;
@Resource
private ShortMessageCheckService shortMessageCheckService;
@Autowired
private IFpRnrSmsInfoService smsInfoService;
@Autowired
private ChangeOrUnbindIccidsClient client;
@Override
public Response enterpriseUnBind(RnrRelationDTO dto) {
Response response = mgRnrRelationClient.saveRnrRelation(dto);
if(!response.isSuccess()){
throw new CuscUserException(response.getCode(),response.getMsg());
}
SmsRequestDTO smsRequestDTO = new SmsRequestDTO();
smsRequestDTO.setBizType(BizTypeEnum.ENTERPRISE_UNBIND.getCode());
smsRequestDTO.setTenantNo(dto.getInfo().getTenantNo());
smsRequestDTO.setPhone(dto.getInfo().getPhone());
//短信参数
List<String> params = new ArrayList<>();
params.add(dto.getInfo().getFullName());
params.add(String.valueOf(dto.getCarNumber()));
smsRequestDTO.setParams(params);
log.warn("企业解绑发送入参{}",JSONObject.toJSONString(smsRequestDTO));
Response<SmsResponseDTO> smsResponseDTOResponse = shortMessageCheckService.sendSms(smsRequestDTO);
log.warn("企业解绑发送回参{}",JSONObject.toJSONString(smsResponseDTOResponse));
if(!smsResponseDTOResponse.isSuccess()){
throw new CuscUserException(smsResponseDTOResponse.getCode(),smsResponseDTOResponse.getMsg());
}
//短信入库
FpRnrSmsInfoDTO fpRnrSmsInfoDTO = new FpRnrSmsInfoDTO();
fpRnrSmsInfoDTO.setIsDelete(0);
fpRnrSmsInfoDTO.setUuid(CuscStringUtils.generateUuid());
fpRnrSmsInfoDTO.setSendPhone(smsRequestDTO.getPhone());
fpRnrSmsInfoDTO.setSendSmsId(smsResponseDTOResponse.getData().getMessageId());
fpRnrSmsInfoDTO.setRnrId(dto.getInfo().getUuid());
fpRnrSmsInfoDTO.setOrderId(dto.getOrder().getUuid());
// fpRnrSmsInfoDTO.setIccids(JSONObject.toJSONString(dto.getCardList().stream().map(c -> c.getIccid())
// .collect(Collectors.toList())));
fpRnrSmsInfoDTO.setSendContent(smsRequestDTO.getParams().toString());
fpRnrSmsInfoDTO.setBizType(MessageBizTypeEnum.UNBIND.getCode());
fpRnrSmsInfoDTO.setCreator(dto.getInfo().getCreator());
fpRnrSmsInfoDTO.setOperator(dto.getInfo().getCreator());
smsInfoService.insert(fpRnrSmsInfoDTO);
//发送延迟队列
RnrOrderDTO rnrOrderDTO = new RnrOrderDTO();
rnrOrderDTO.setUuid(dto.getOrder().getUuid());
client.sendMSMToMQ(rnrOrderDTO);
return smsResponseDTOResponse;
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cusc.nirvana.common.result.PageResult;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.rds.mybatis.PageHelper;
import com.cusc.nirvana.user.rnr.fp.constants.CryptKeyHelper;
import com.cusc.nirvana.user.rnr.fp.converter.FpCarInfoConverter;
import com.cusc.nirvana.user.rnr.fp.dao.FpCarInfoDao;
import com.cusc.nirvana.user.rnr.fp.dao.entity.FpCarInfoPO;
import com.cusc.nirvana.user.rnr.fp.dto.CarInfoBindingDTO;
import com.cusc.nirvana.user.rnr.fp.dto.FpCarInfoDTO;
import com.cusc.nirvana.user.rnr.fp.service.IFpCarInfoService;
import com.cusc.nirvana.user.rnr.mg.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.util.CuscStringUtils;
import com.cusc.nirvana.user.util.crypt.DataCryptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* 车辆信息表(FpCarInfo)表服务实现类
*
* @author yuy336
* @since 2022-06-28 19:46:25
*/
@Service
@Slf4j
public class FpCarInfoServiceImpl extends ServiceImpl<FpCarInfoDao, FpCarInfoPO> implements IFpCarInfoService {
@Resource
private FpCarInfoDao fpCarInfoDao;
@Autowired
private DataCryptService dataCryptService ;
/**
* 通过UUID查询单条数据
*
* @param bean
* @return 实例对象
*/
@Override
public FpCarInfoDTO getByUuid(FpCarInfoDTO bean) {
FpCarInfoPO record = this.getPoByUuid(bean.getUuid());;
return FpCarInfoConverter.INSTANCE.poToDto(record);
}
/**
* 通过查询条件查询集合数据
*
* @param bean
* @return 集合对象
*/
@Override
public List<FpCarInfoDTO> queryByList(FpCarInfoDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("vin",bean.getVin());
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.orderByDesc("create_time");
List<FpCarInfoPO> record = this.list(queryWrapper);
return FpCarInfoConverter.INSTANCE.poListToDtoList(record);
}
/**
* 分页查询
*
* @param bean 筛选条件
* @return 查询结果
*/
@Override
public PageResult<FpCarInfoDTO> queryByPage(FpCarInfoDTO bean) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq(!StringUtils.isEmpty(bean.getOrgid()),"orgId",bean.getOrgid());
queryWrapper.eq(!StringUtils.isEmpty(bean.getVin()),"vin", CryptKeyHelper.encrypt(bean.getVin()));
queryWrapper.eq(!StringUtils.isEmpty(bean.getOrgid()),"orgId",bean.getOrgid());
queryWrapper.le(!StringUtils.isEmpty(bean.getEndTime()),"create_time",bean.getEndTime());
queryWrapper.ge(!StringUtils.isEmpty(bean.getStartTime()),"create_time",bean.getStartTime());
queryWrapper.orderByDesc("create_time");
Page<FpCarInfoPO> page =
this.page(new Page<>(bean.getCurrPage(), bean.getPageSize()), queryWrapper);
return PageHelper.convert(page, FpCarInfoDTO.class);
}
/**
* 新增数据
*
* @param bean 实例对象
* @return 实例对象
*/
@Override
@Transactional
public FpCarInfoDTO insert(FpCarInfoDTO bean) {
FpCarInfoPO fpCarInfoPO = FpCarInfoConverter.INSTANCE.dtoToPo(bean);
fpCarInfoPO.setUuid(CuscStringUtils.generateUuid());
this.save(fpCarInfoPO);
bean.setUuid(fpCarInfoPO.getUuid());
return bean;
}
/**
* @author: jk
* @description: 批量插入
* @date: 2022/6/29 14:05
* @version: 1.0
*/
@Override
@Transactional
public Response addBatch(CarInfoBindingDTO bean) {
boolean flag = true;
if(!CollectionUtils.isEmpty(bean.getBindingList())) {
try {
log.warn("addBatch入参{}", JSONObject.toJSONString(bean));
List<FpCarInfoPO> list = this.dtoListToPoList(bean.getBindingList());
int tota = fpCarInfoDao.batchSaveOrUpdate(list);
if(tota>0){
flag =true;
}else {
flag =false;
}
} catch (Exception e) {
log.error("车辆信息入库失败",e);
flag = false;
}
}
return flag ? Response.createSuccess():Response.createError();
}
public List<FpCarInfoPO> dtoListToPoList(List<FpCarInfoDTO> dtos) {
if ( dtos == null ) {
return null;
}
List<FpCarInfoPO> list = new ArrayList<FpCarInfoPO>( dtos.size() );
for ( FpCarInfoDTO fpCarInfoDTO : dtos ) {
list.add( dtoToPo( fpCarInfoDTO ) );
}
return list;
}
public FpCarInfoPO dtoToPo(FpCarInfoDTO bean) {
if ( bean == null ) {
return null;
}
FpCarInfoPO fpCarInfoPO = new FpCarInfoPO();
fpCarInfoPO.setId( bean.getId() );
fpCarInfoPO.setIsDelete( bean.getIsDelete() );
fpCarInfoPO.setCreateTime( bean.getCreateTime() );
fpCarInfoPO.setUpdateTime( bean.getUpdateTime() );
fpCarInfoPO.setCreator( bean.getCreator() );
fpCarInfoPO.setUuid( bean.getUuid() );
fpCarInfoPO.setNameVehicleEnterprise( bean.getNameVehicleEnterprise() );
fpCarInfoPO.setVin( dataCryptService.encryptData(bean.getVin()) );
fpCarInfoPO.setVehicleType( bean.getVehicleType() );
fpCarInfoPO.setPlaceOfOriginOfVehicle( bean.getPlaceOfOriginOfVehicle() );
fpCarInfoPO.setVehicleDepartment( bean.getVehicleDepartment() );
fpCarInfoPO.setVehicleName( bean.getVehicleName() );
fpCarInfoPO.setVehicleNum( bean.getVehicleNum() );
fpCarInfoPO.setVehicleModel( bean.getVehicleModel() );
fpCarInfoPO.setBodyColor( bean.getBodyColor() );
fpCarInfoPO.setFuelType( bean.getFuelType() );
fpCarInfoPO.setEngineNum( bean.getEngineNum() );
fpCarInfoPO.setMotorNum( bean.getMotorNum() );
fpCarInfoPO.setVehicleDepartureTime( bean.getVehicleDepartureTime() );
fpCarInfoPO.setVehicleSalesTime( bean.getVehicleSalesTime() );
fpCarInfoPO.setVehicleSalesUpdateTime( bean.getVehicleSalesUpdateTime() );
fpCarInfoPO.setLicensePlateNumber( dataCryptService.encryptData(bean.getLicensePlateNumber()) );
fpCarInfoPO.setVehicleChannelName( bean.getVehicleChannelName() );
fpCarInfoPO.setVehicleChannelType( bean.getVehicleChannelType() );
fpCarInfoPO.setVehicleStaffName( dataCryptService.encryptData(bean.getVehicleStaffName()) );
fpCarInfoPO.setVehicleLogginAddress( bean.getVehicleLogginAddress() );
fpCarInfoPO.setOrgid( bean.getOrgid() );
fpCarInfoPO.setTenantno( bean.getTenantno() );
fpCarInfoPO.setOperator( bean.getOperator() );
fpCarInfoPO.setTagId( bean.getTagId() );
return fpCarInfoPO;
}
/**
* 修改数据
*
* @param bean 实例对象
* @return 实例对象
*/
@Override
@Transactional
public FpCarInfoDTO update(FpCarInfoDTO bean) {
FpCarInfoPO fpCarInfoPO = this.getPoByUuid(bean.getUuid());
if(fpCarInfoPO == null){
return null;
}
FpCarInfoPO tmpBean = FpCarInfoConverter.INSTANCE.dtoToPo(bean);
tmpBean.setId(fpCarInfoPO.getId());
this.updateById(tmpBean);
return bean;
}
/**
* 通过主键删除数据
* @param bean 实例对象
* @return 是否成功
*/
@Override
@Transactional
public boolean deleteById(FpCarInfoDTO bean) {
FpCarInfoPO fpCarInfoPO = this.getPoByUuid(bean.getUuid());
if (fpCarInfoPO == null) {
return false;
}
FpCarInfoPO tmpBean = new FpCarInfoPO();
tmpBean.setId(fpCarInfoPO.getId());
tmpBean.setIsDelete(CommonDeleteEnum.DELETED.getCode());
return this.updateById(tmpBean);
}
/**
* 通过UUID查询单条数据
*
* @param uuid
* @return 实例对象
*/
private FpCarInfoPO getPoByUuid(String uuid) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", uuid);
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
return this.getOne(queryWrapper);
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.alibaba.fastjson.JSON;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.rnr.fp.common.ResponseCode;
import com.cusc.nirvana.user.rnr.fp.constants.BizTypeEnum;
import com.cusc.nirvana.user.rnr.fp.dto.*;
import com.cusc.nirvana.user.rnr.fp.service.IFpCardUnBindService;
import com.cusc.nirvana.user.rnr.fp.service.IFpRnrSmsInfoService;
import com.cusc.nirvana.user.rnr.fp.service.ShortMessageCheckService;
import com.cusc.nirvana.user.rnr.mg.client.ChangeOrUnbindIccidsClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrCardInfoClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrInfoClient;
import com.cusc.nirvana.user.rnr.mg.client.RnrOrderClient;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrCardInfoDTO;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrInfoDTO;
import com.cusc.nirvana.user.rnr.mg.dto.RnrOrderDTO;
import com.cusc.nirvana.user.rnr.mg.dto.RnrRelationDTO;
import com.cusc.nirvana.user.util.CuscStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
@Service
@Slf4j
public class FpCardUnBindServiceImpl implements IFpCardUnBindService {
@Resource
private MgRnrCardInfoClient cardInfoClient;
@Resource
private MgRnrInfoClient infoClient;
@Autowired
private ShortMessageCheckService messageCheckService;
@Autowired
private IFpRnrSmsInfoService smsInfoService;
@Resource
private RnrOrderClient orderClient;
@Resource
private ChangeOrUnbindIccidsClient iccidsClient;
@Value("${message.callback.timeout:120}")
private int timeOut;
/**
* 车主实名解绑
* @return
*/
@Override
public Response<Boolean> ownerUnbind(RnrRelationDTO relationDTO){
log.info("解绑fp入参: {}", JSON.toJSONString(relationDTO));
Response orderResponse = orderClient.add(relationDTO.getOrder());
if(!orderResponse.isSuccess()){
return Response.createError("保存工单失败");
}
return cardInfoClient.updateBatch(relationDTO.getCardList());
}
@Override
public Response<MgRnrInfoDTO> getUserInfo(FpVehicleCardRnrDTO cardRnrDTO){
log.info("解绑fp获取实名信息入参: {}", JSON.toJSONString(cardRnrDTO));
MgRnrInfoDTO mgRnrInfoDTO = new MgRnrInfoDTO();
mgRnrInfoDTO.setUuid(cardRnrDTO.getRnrId());
log.info("解绑mg获取实名信息入参: {}", JSON.toJSONString(mgRnrInfoDTO));
Response<MgRnrInfoDTO> byUuid = infoClient.getByUuid(mgRnrInfoDTO);
log.info("解绑mg获取实名信息出参: {}", JSON.toJSONString(byUuid));
if(!byUuid.isSuccess() || byUuid.getData() == null){
return Response.createError("获取实名人信息失败");
}
return byUuid;
}
//发送短信
@Override
public Response<FpRnrSmsInfoDTO> sendUnbindSMS(FpSendMessageDTO sendMessageDTO) {
log.info("解绑fp发短信入参: {}", JSON.toJSONString(sendMessageDTO));
Response<SmsResponseDTO> smsResponseDTOResponse = messageCheckService.sendUnbindSms(sendMessageDTO.getSmsRequestDTO(), sendMessageDTO.getRnrid(), sendMessageDTO.getIccidLists());
if(!smsResponseDTOResponse.isSuccess() || smsResponseDTOResponse.getData() == null){
return Response.createError("短信发送失败");
}
log.info("解绑短信返回值: {}",JSON.toJSONString(smsResponseDTOResponse));
//短信入库
SmsRequestDTO smsRequestDto = sendMessageDTO.getSmsRequestDTO();
FpRnrSmsInfoDTO fpRnrSmsInfoDTO = new FpRnrSmsInfoDTO();
fpRnrSmsInfoDTO.setIsDelete(0);
fpRnrSmsInfoDTO.setCreateTime(new Date(System.currentTimeMillis()));
fpRnrSmsInfoDTO.setUuid(CuscStringUtils.generateUuid());
fpRnrSmsInfoDTO.setSendPhone(sendMessageDTO.getSmsRequestDTO().getPhone());
fpRnrSmsInfoDTO.setSendSmsId(smsResponseDTOResponse.getData().getMessageId());
fpRnrSmsInfoDTO.setRnrId(sendMessageDTO.getRnrid());
fpRnrSmsInfoDTO.setIccids(sendMessageDTO.getIccidLists());
fpRnrSmsInfoDTO.setSendContent(sendMessageDTO.getSmsRequestDTO().getParams().toString());
fpRnrSmsInfoDTO.setBizType(wrapBizType(smsRequestDto.getBizType()));
fpRnrSmsInfoDTO.setCreator(sendMessageDTO.getUser());
fpRnrSmsInfoDTO.setOperator(sendMessageDTO.getUser());
fpRnrSmsInfoDTO.setOrderId(sendMessageDTO.getOrderId());
FpRnrSmsInfoDTO insert = smsInfoService.insert(fpRnrSmsInfoDTO);
return Response.createSuccess(insert);
}
@Override
public Response<List<MgRnrCardInfoDTO>> getCardList(FpVehicleCardRnrDTO cardRnrDTO) {
log.info("解绑fp获取iccid列表入参: {}", JSON.toJSONString(cardRnrDTO));
MgRnrCardInfoDTO bean = new MgRnrCardInfoDTO();
bean.setIotId(cardRnrDTO.getVin());
// bean.setRnrBizzType(RnrBizzTypeEnum.Unbound.getCode());
return cardInfoClient.queryBindListByVin(bean);
}
@Override
public Response<FpRnrSmsInfoDTO> getMessageStatus(FpRnrSmsInfoDTO bean) {
log.info("解绑fp获取短信状态入参: {}", JSON.toJSONString(bean));
FpRnrSmsInfoDTO poByMessageId = smsInfoService.getPoByPhoneNo(bean);
return Response.createSuccess(poByMessageId);
}
//短信回调
@Override
public Response<FpRnrSmsInfoDTO> receiveMessage(UnbindReceiceSMSDTO receiceSMSDTO) {
log.info("解绑fp获取短信回调入参: {}", JSON.toJSONString(receiceSMSDTO));
FpRnrSmsInfoDTO fpRnrSmsInfoDTO = new FpRnrSmsInfoDTO();
fpRnrSmsInfoDTO.setSendPhone(receiceSMSDTO.getPhoneNumber());
fpRnrSmsInfoDTO.setSendSmsId(receiceSMSDTO.getMessageId());
FpRnrSmsInfoDTO poByPhoneNo = smsInfoService.getPoByPhoneNo(fpRnrSmsInfoDTO);
if(poByPhoneNo == null){
return Response.createError("获取短信内容失败");
}
poByPhoneNo.setReceivePhone(receiceSMSDTO.getPhoneNumber());
poByPhoneNo.setReceiveSmsId(receiceSMSDTO.getMessageId());
poByPhoneNo.setReceiveContent(receiceSMSDTO.getReplyContent());
return Response.createSuccess(smsInfoService.update(poByPhoneNo));
}
@Override
public Response<RnrOrderDTO> insertOrder(RnrOrderDTO dto){
Response response = orderClient.add(dto);
if(!response.isSuccess()){
return Response.createError(response.getMsg(),response.getCode());
}
iccidsClient.sendMSMToMQ(dto);
return response;
}
@Override
public Response<RnrOrderDTO> getOrderStatus(RnrOrderDTO dto){
Response<RnrOrderDTO> dtoResponse = orderClient.getByUuid(dto);
if(!dtoResponse.isSuccess()){
return Response.createError(dtoResponse.getMsg(),dtoResponse.getCode());
}
return dtoResponse;
}
@Override
public Response checkReceiveMessageTime(RnrOrderDTO dto){
long currentTimeMillis = System.currentTimeMillis();
//查询短信信息
FpRnrSmsInfoDTO fpRnrSmsInfoDTO = new FpRnrSmsInfoDTO();
fpRnrSmsInfoDTO.setOrderId(dto.getUuid());
log.info("fp解绑查询短信状态:{}",JSON.toJSONString(fpRnrSmsInfoDTO));
List<FpRnrSmsInfoDTO> fpRnrSmsInfoDTOS = smsInfoService.queryByOrderId(fpRnrSmsInfoDTO);
log.info("fp解绑查询短信:{}",JSON.toJSONString(fpRnrSmsInfoDTOS));
if (CollectionUtils.isEmpty(fpRnrSmsInfoDTOS)) {
return Response.createError("获取短信信息失败");
}
//校验时间
long time = fpRnrSmsInfoDTOS.get(0).getCreateTime().getTime();
log.info("判断超时,{},{},{},{}", currentTimeMillis, timeOut, time, currentTimeMillis - timeOut * 1000);
if (currentTimeMillis - timeOut * 1000 > time) {
log.info("短信回复超时,设置成失败状态");
return Response.createError("回复短信超时");
}
return Response.createSuccess("短信校验未超时");
}
@Override
public Response<RnrOrderDTO> updateOrder(RnrOrderDTO dto){
Response response = orderClient.updateOrderStatus(dto);
if(!response.isSuccess()){
//return Response.createError(response.getMsg(),response.getCode());
throw new CuscUserException(ResponseCode.SYSTEM_ERROR.getCode(),"更新工单失败");
}
return response;
}
private Integer wrapBizType(String bizType) {
Integer rv = MessageBizTypeEnum.UBIND.getCode();
if (BizTypeEnum.CHANGETBOX.getCode().equalsIgnoreCase(bizType)) {
rv = MessageBizTypeEnum.CHANGETBOX.getCode();
}
return rv;
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.MapUtils;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.rnr.fp.dto.FpDirectTboxChangeDTO;
import com.cusc.nirvana.user.rnr.fp.service.IFpChangeTboxService;
import com.cusc.nirvana.user.rnr.mg.client.*;
import com.cusc.nirvana.user.rnr.mg.constants.RnrBizzTypeEnum;
import com.cusc.nirvana.user.rnr.mg.constants.RnrOrderStatusEnum;
import com.cusc.nirvana.user.rnr.mg.constants.RnrStatus;
import com.cusc.nirvana.user.rnr.mg.dto.MgCardNoticeDTO;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrCardInfoDTO;
import com.cusc.nirvana.user.rnr.mg.dto.RnrOrderDTO;
import com.cusc.nirvana.user.rnr.mg.dto.RnrRelationDTO;
import com.cusc.nirvana.user.util.CuscStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author changh
* @date 2022/4/24
*/
@Service
@Slf4j
public class FpChangeTboxServiceImpl implements IFpChangeTboxService {
@Resource
private MgRnrCardInfoClient cardInfoClient;
@Resource
private MgRnrRelationClient rnrRelationClient;
@Resource
private MgSurplusBindClient mgSurplusBindClient;
@Resource
private IFpChangeTboxService changeTboxService;
@Resource
private RnrOrderClient rnrOrderClient;
@Resource
private OrgSimRelClient orgSimRelClient;
/**
* 卡换绑
*
* @return
*/
@Override
public Response submit(RnrRelationDTO relationDTO) {
log.info("换卡fp入参:{}", JSON.toJSONString(relationDTO));
List<MgRnrCardInfoDTO> unbindCardInfoDTOList = new ArrayList<>();
List<MgRnrCardInfoDTO> bindCardInfoDTOList = new ArrayList<>();
for (int i = 0; i < relationDTO.getCardList().size(); i++) {
if (i < relationDTO.getCardList().size() / 2) {
unbindCardInfoDTOList.add(relationDTO.getCardList().get(i));
} else {
bindCardInfoDTOList.add(relationDTO.getCardList().get(i));
}
}
Response response = unbindCardList(unbindCardInfoDTOList);
if (!response.isSuccess()) {
return Response.createError("卡解绑失败");
}
return rnrRelationClient.saveRnrRelation(relationDTO);
}
@Override
public Response<Boolean> unbindCardList(List<MgRnrCardInfoDTO> cardInfoDTOList) {
log.info("换卡fp解绑入参:{}", JSON.toJSONString(cardInfoDTOList));
for (MgRnrCardInfoDTO cardInfo : cardInfoDTOList) {
cardInfo.setRnrStatus(RnrStatus.UNBOUND.getCode());
//cardInfo.setRnrBizzType(RnrBizzTypeEnum.ChangeBinding.getCode());
}
return cardInfoClient.updateBatch(cardInfoDTOList);
}
@Override
public Response<Boolean> bindCardList(List<MgRnrCardInfoDTO> cardInfoDTOList) {
log.info("换卡fp绑定入参:{}", JSON.toJSONString(cardInfoDTOList));
return cardInfoClient.insertBatch(cardInfoDTOList);
}
@Override
public Response checkNewIccid(List<String> newCards) {
log.info("换卡fp校验新iccid实名状态入参:{}", JSON.toJSONString(newCards));
boolean checkResult = true;
for (String iccid : newCards) {
MgRnrCardInfoDTO infoDTO = new MgRnrCardInfoDTO();
infoDTO.setIccid(iccid);
Response<MgRnrCardInfoDTO> oneByIccid = cardInfoClient.getOneByIccid(infoDTO);
log.info("换卡fp校验新iccid实名状态出参:{}", JSON.toJSONString(oneByIccid));
if (!oneByIccid.isSuccess() || oneByIccid.getData() != null) {
checkResult = false;
break;
}
}
return Response.createSuccess(checkResult);
}
@Override
public Response queryResult() {
//根据新的rnrid,查询短信状态--这里是从哪里查询
return null;
}
@Override
public Response directChangeBox(FpDirectTboxChangeDTO tboxChangeDTO) {
List<String> oldIccids = new ArrayList<>(tboxChangeDTO.getNewOldIccidRelMap().values());
List<MgRnrCardInfoDTO> oldCards = getOldIccidDTO(oldIccids, tboxChangeDTO.getVin());
List<String> iccidList = oldCards.stream().map(a->a.getIccid()).collect(Collectors.toList());
if (oldCards == null || oldCards.size() < 1) {
return Response.createError("待解绑卡存在未实名");
}
List<MgRnrCardInfoDTO> newCards = createCardInfoDTOS(tboxChangeDTO, oldCards);
Response unbindCards = changeTboxService.unbindCardList(oldCards);
Response bindCards = changeTboxService.bindCardList(newCards);
Response oldList = orgSimRelClient.updateBindIccid(iccidList);
// orgSimRelClient.u
//发送mq通知
List<MgCardNoticeDTO> mgCardNoticeDTOS = createMqDTO(newCards, oldCards);
MgRnrCardInfoDTO mgRnrCardInfoDTO = new MgRnrCardInfoDTO();
List<MgRnrCardInfoDTO> mgRnrCardInfoDTOList = new ArrayList<>();
for(MgRnrCardInfoDTO mgRnrCardInfo:newCards){
mgRnrCardInfoDTO.setIccid(mgRnrCardInfo.getIccid());
mgRnrCardInfoDTO.setIotId(mgRnrCardInfo.getIotId());
mgRnrCardInfoDTOList.add(mgRnrCardInfoDTO);
}
orgSimRelClient.updateVin(mgRnrCardInfoDTOList);
mgSurplusBindClient.sendMQ(mgCardNoticeDTOS);
if (bindCards.isSuccess() && unbindCards.isSuccess() && oldList.isSuccess()) {
return Response.createSuccess("更换设备成功");
} else {
return Response.createSuccess("更换设备失败", bindCards.getData());
}
}
private List<MgRnrCardInfoDTO> getOldIccidDTO(List<String> iccids, String vin) {
List<MgRnrCardInfoDTO> cardInfoDTOS = new ArrayList<>();
MgRnrCardInfoDTO dto = new MgRnrCardInfoDTO();
dto.setIotId(vin);
Response<List<MgRnrCardInfoDTO>> listResponse = cardInfoClient.queryListByVin(dto);
if (!listResponse.isSuccess()) {
return cardInfoDTOS;
}
cardInfoDTOS = listResponse.getData().stream().filter(t -> iccids.contains(t.getIccid()) && t.getRnrStatus() == RnrStatus.RNR.getCode()).collect(Collectors.toList());
return cardInfoDTOS;
}
private List<MgRnrCardInfoDTO> createCardInfoDTOS(FpDirectTboxChangeDTO tboxChangeDTO, List<MgRnrCardInfoDTO> oldCards) {
List<String> newIccids = new ArrayList<>(tboxChangeDTO.getNewOldIccidRelMap().keySet());
Map<String, MgRnrCardInfoDTO> oldCardMap = new HashMap<>();
oldCards.forEach(mgRnrCardInfoDTO -> oldCardMap.put(mgRnrCardInfoDTO.getIccid(), mgRnrCardInfoDTO));
List<MgRnrCardInfoDTO> cardInfoDTOS = new ArrayList<>();
Map<String, String> relMap = tboxChangeDTO.getNewOldIccidRelMap();
for (int i = 0; i < newIccids.size(); i++) {
String iccid = newIccids.get(i);
MgRnrCardInfoDTO mgRnrCardInfoDTO = new MgRnrCardInfoDTO();
mgRnrCardInfoDTO.setUuid(CuscStringUtils.generateUuid());
mgRnrCardInfoDTO.setIccid(iccid);
mgRnrCardInfoDTO.setTenantNo(tboxChangeDTO.getTenantNo());
mgRnrCardInfoDTO.setIotId(tboxChangeDTO.getVin());
mgRnrCardInfoDTO.setRnrId(tboxChangeDTO.getRnrId());
mgRnrCardInfoDTO.setOrderId(tboxChangeDTO.getOrderUuid());
mgRnrCardInfoDTO.setCreator(tboxChangeDTO.getOperator());
mgRnrCardInfoDTO.setOperator(tboxChangeDTO.getOperator());
mgRnrCardInfoDTO.setRnrBizzType(RnrBizzTypeEnum.ChangeBinding.getCode());
mgRnrCardInfoDTO.setRnrStatus(RnrStatus.RNR.getCode());
mgRnrCardInfoDTO.setRoutingKey(tboxChangeDTO.getRoutingKey());
//根据新旧卡的对应关系找到老卡的uuid进行赋值新卡字段oldCardId
if (MapUtils.isNotEmpty(relMap)) {
String oldIccid = relMap.get(iccid);
MgRnrCardInfoDTO oldCardInfo = oldCardMap.get(oldIccid);
if (null != oldCardInfo) {
mgRnrCardInfoDTO.setOldCardId(oldCardInfo.getUuid());
}
}
cardInfoDTOS.add(mgRnrCardInfoDTO);
}
return cardInfoDTOS;
}
private List<MgCardNoticeDTO> createMqDTO(List<MgRnrCardInfoDTO> newIccids, List<MgRnrCardInfoDTO> oldIccids) {
List<MgCardNoticeDTO> cardNoticeDTOS = new ArrayList<>();
for (int i = 0; i < newIccids.size(); i++) {
RnrOrderDTO rnrOrderDTO = new RnrOrderDTO();
rnrOrderDTO.setUuid(newIccids.get(i).getOrderId());
Response<RnrOrderDTO> response = rnrOrderClient.getByUuid(rnrOrderDTO);
if(!response.isSuccess()){
throw new CuscUserException(response.getCode(),response.getMsg());
}
MgCardNoticeDTO mgCardNoticeDTO = new MgCardNoticeDTO();
mgCardNoticeDTO.setIccid(newIccids.get(i).getIccid());
mgCardNoticeDTO.setOldIccid(oldIccids.get(i).getIccid());
//mgCardNoticeDTO.setRnrId(newIccids.get(i).getRnrId());
mgCardNoticeDTO.setTenantNo(newIccids.get(i).getTenantNo());
mgCardNoticeDTO.setVin(newIccids.get(i).getIotId());
mgCardNoticeDTO.setRnrBizzType(newIccids.get(i).getRnrBizzType());
mgCardNoticeDTO.setOrderId(newIccids.get(i).getOrderId());
mgCardNoticeDTO.setResultCode(RnrOrderStatusEnum.PASS.getCode());
mgCardNoticeDTO.setOrgId(response.getData().getOrgId());
//mgCardNoticeDTO.setOperationType(RnrBizzTypeEnum.ChangeBinding.getCode());
cardNoticeDTOS.add(mgCardNoticeDTO);
}
return cardNoticeDTOS;
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cusc.nirvana.common.result.PageResult;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.rds.mybatis.PageHelper;
import com.cusc.nirvana.user.eiam.client.OrganizationClient;
import com.cusc.nirvana.user.eiam.dto.OrganizationDTO;
import com.cusc.nirvana.user.rnr.fp.common.ResponseCode;
import com.cusc.nirvana.user.rnr.fp.converter.FpRnrProtocolManageConverter;
import com.cusc.nirvana.user.rnr.fp.dao.FpRnrProtocolManageDao;
import com.cusc.nirvana.user.rnr.fp.dao.entity.FpRnrProtocolManagePO;
import com.cusc.nirvana.user.rnr.fp.dto.FpRnrProtocolManageDTO;
import com.cusc.nirvana.user.rnr.fp.service.IFpRnrProtocolManageService;
import com.cusc.nirvana.user.rnr.fp.service.OrganizationService;
import com.cusc.nirvana.user.rnr.mg.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
/**
* (FpRnrProtocolManage)表服务实现类
*
* @author yuy336
* @since 2022-06-01 10:52:45
*/
@Service
public class FpRnrProtocolManageServiceImpl extends ServiceImpl<FpRnrProtocolManageDao, FpRnrProtocolManagePO> implements IFpRnrProtocolManageService {
@Autowired
private OrganizationService organizationService;
@Autowired
private OrganizationClient organizationClient;
/**
* 通过UUID查询单条数据
*
* @param bean
* @return 实例对象
*/
@Override
public FpRnrProtocolManageDTO getByUuid(FpRnrProtocolManageDTO bean) {
FpRnrProtocolManagePO record = this.getPoByUuid(bean.getUuid());;
return FpRnrProtocolManageConverter.INSTANCE.poToDto(record);
}
/**
* 通过查询条件查询集合数据
*
* @param bean
* @return 集合对象
*/
@Override
public Response<List<FpRnrProtocolManageDTO>> queryByList(FpRnrProtocolManageDTO bean) {
OrganizationDTO organizationDTO = new OrganizationDTO();
organizationDTO.setUuid(bean.getOrgId());
organizationDTO.setTenantNo(bean.getTenantNo());
String ordId = "";
if(!StringUtils.isEmpty(bean.getType())&&"1".equals(bean.getType())){
organizationDTO.setUuid(null);
organizationDTO.setParentId("0");
organizationDTO.setBizType(1);
Response<List<OrganizationDTO>> response = organizationClient.queryByList(organizationDTO);
if(!response.isSuccess()){
return Response.createError(response.getMsg(), response.getCode());
}
if(null == response.getData()){
return Response.createError(ResponseCode.DATA_IS_NULL.getMsg(), ResponseCode.DATA_IS_NULL.getCode());
}
ordId = response.getData().get(0).getUuid();
}else {
//获取车企组织
Response<OrganizationDTO> response = organizationService.getCarSubOrganByQueryCode(organizationDTO);
if(!response.isSuccess()){
return Response.createError(response.getMsg(), response.getCode());
}
ordId = response.getData().getUuid();
}
bean.setOrgId(ordId);
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.eq("org_id",bean.getOrgId());
queryWrapper.orderByDesc("create_time");
List<FpRnrProtocolManagePO> record = this.list(queryWrapper);
return Response.createSuccess(FpRnrProtocolManageConverter.INSTANCE.poListToDtoList(record));
}
/**
* 分页查询
*
* @param bean 筛选条件
* @return 查询结果
*/
@Override
public PageResult<FpRnrProtocolManageDTO> queryByPage(FpRnrProtocolManageDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.orderByDesc("create_time");
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
Page<FpRnrProtocolManagePO> page =
this.page(new Page<>(bean.getCurrPage(), bean.getPageSize()), queryWrapper);
return PageHelper.convert(page, FpRnrProtocolManageDTO.class);
}
/**
* 新增数据
*
* @param bean 实例对象
* @return 实例对象
*/
@Override
@Transactional
public FpRnrProtocolManageDTO insert(FpRnrProtocolManageDTO bean) {
FpRnrProtocolManagePO fpRnrProtocolManagePO = FpRnrProtocolManageConverter.INSTANCE.dtoToPo(bean);
fpRnrProtocolManagePO.setUuid(CuscStringUtils.generateUuid());
this.save(fpRnrProtocolManagePO);
bean.setUuid(fpRnrProtocolManagePO.getUuid());
return bean;
}
/**
* 修改数据
*
* @param bean 实例对象
* @return 实例对象
*/
@Override
@Transactional
public FpRnrProtocolManageDTO update(FpRnrProtocolManageDTO bean) {
FpRnrProtocolManagePO fpRnrProtocolManagePO = this.getPoByUuid(bean.getUuid());
if(fpRnrProtocolManagePO == null){
return null;
}
FpRnrProtocolManagePO tmpBean = FpRnrProtocolManageConverter.INSTANCE.dtoToPo(bean);
tmpBean.setId(fpRnrProtocolManagePO.getId());
this.updateById(tmpBean);
return bean;
}
/**
* 通过主键删除数据
* @param bean 实例对象
* @return 是否成功
*/
@Override
@Transactional
public boolean deleteById(FpRnrProtocolManageDTO bean) {
FpRnrProtocolManagePO fpRnrProtocolManagePO = this.getPoByUuid(bean.getUuid());
if (fpRnrProtocolManagePO == null) {
return false;
}
FpRnrProtocolManagePO tmpBean = new FpRnrProtocolManagePO();
tmpBean.setId(fpRnrProtocolManagePO.getId());
tmpBean.setIsDelete(CommonDeleteEnum.DELETED.getCode());
return this.updateById(tmpBean);
}
/**
* 通过UUID查询单条数据
*
* @param uuid
* @return 实例对象
*/
private FpRnrProtocolManagePO getPoByUuid(String uuid) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", uuid);
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
return this.getOne(queryWrapper);
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cusc.nirvana.user.rnr.fp.converter.FpRnrRelationInfoConverter;
import com.cusc.nirvana.user.rnr.fp.dao.FpRnrRelationInfoDao;
import com.cusc.nirvana.user.rnr.fp.dao.entity.FpRnrRelationInfoPO;
import com.cusc.nirvana.user.rnr.fp.dto.BindUserInfoDTO;
import com.cusc.nirvana.user.rnr.fp.dto.FpRnrRelationInfoDTO;
import com.cusc.nirvana.user.rnr.fp.service.IFpRnrRelationInfoService;
import com.cusc.nirvana.user.rnr.mg.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 实名关联信息(FpRnrRelationInfo)表服务实现类
*
* @author yuy336
* @since 2022-04-14 20:43:07
*/
@Service
public class FpRnrRelationInfoServiceImpl extends ServiceImpl<FpRnrRelationInfoDao, FpRnrRelationInfoPO> implements IFpRnrRelationInfoService {
/**
* 通过UUID查询单条数据
*
* @param bean
* @return 实例对象
*/
@Override
public FpRnrRelationInfoDTO getByUuid(FpRnrRelationInfoDTO bean) {
FpRnrRelationInfoPO record = this.getPoByUuid(bean.getUuid());;
return FpRnrRelationInfoConverter.INSTANCE.poToDto(record);
}
/**
* 通过查询条件查询集合数据
*
* @param bean
* @return 集合对象
*/
@Override
public List<FpRnrRelationInfoDTO> queryByList(FpRnrRelationInfoDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.orderByDesc("create_time");
List<FpRnrRelationInfoPO> record = this.list(queryWrapper);
return FpRnrRelationInfoConverter.INSTANCE.poListToDtoList(record);
}
/**
* 新增数据
*
* @param bean 实例对象
* @return 实例对象
*/
@Override
@Transactional
public FpRnrRelationInfoDTO insert(FpRnrRelationInfoDTO bean) {
FpRnrRelationInfoPO fpRnrRelationInfoPO = FpRnrRelationInfoConverter.INSTANCE.dtoToPo(bean);
fpRnrRelationInfoPO.setUuid(CuscStringUtils.generateUuid());
this.save(fpRnrRelationInfoPO);
bean.setUuid(fpRnrRelationInfoPO.getUuid());
return bean;
}
/**
* 修改数据
*
* @param bean 实例对象
* @return 实例对象
*/
@Override
@Transactional
public FpRnrRelationInfoDTO update(FpRnrRelationInfoDTO bean) {
FpRnrRelationInfoPO fpRnrRelationInfoPO = this.getPoByUuid(bean.getUuid());
if(fpRnrRelationInfoPO == null){
return null;
}
FpRnrRelationInfoPO tmpBean = FpRnrRelationInfoConverter.INSTANCE.dtoToPo(bean);
tmpBean.setId(fpRnrRelationInfoPO.getId());
this.updateById(tmpBean);
return bean;
}
/**
* 通过主键删除数据
* @param bean 实例对象
* @return 是否成功
*/
@Override
@Transactional
public boolean deleteById(FpRnrRelationInfoDTO bean) {
FpRnrRelationInfoPO fpRnrRelationInfoPO = this.getPoByUuid(bean.getUuid());
if (fpRnrRelationInfoPO == null) {
return false;
}
FpRnrRelationInfoPO tmpBean = new FpRnrRelationInfoPO();
tmpBean.setId(fpRnrRelationInfoPO.getId());
tmpBean.setIsDelete(CommonDeleteEnum.DELETED.getCode());
return this.updateById(tmpBean);
}
//查询绑定状态
@Override
public List<FpRnrRelationInfoDTO> queryByUserId(FpRnrRelationInfoDTO bean) {
List<FpRnrRelationInfoPO> record = this.getPoByUserId(bean.getUserId());
return FpRnrRelationInfoConverter.INSTANCE.poListToDtoList(record);
}
//绑定实名
@Override
public Boolean bindByUserId(BindUserInfoDTO bean){
//todo 绑定实名信息
return true;
}
//解绑
@Override
public Boolean disableBindByUserId(FpRnrRelationInfoDTO bean){
bean.setUserId(null);
FpRnrRelationInfoDTO insert = update(bean);
if(insert != null){
return true;
}else {
return false;
}
}
/**
* 通过UUID查询单条数据
*
* @param uuid
* @return 实例对象
*/
private FpRnrRelationInfoPO getPoByUuid(String uuid) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", uuid);
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
return this.getOne(queryWrapper);
}
private List<FpRnrRelationInfoPO> getPoByUserId(String userId) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("user_id", userId);
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.orderByDesc("create_time");
return this.list(queryWrapper);
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cusc.nirvana.common.result.PageResult;
import com.cusc.nirvana.rds.mybatis.PageHelper;
import com.cusc.nirvana.user.rnr.fp.converter.FpRnrSmsInfoConverter;
import com.cusc.nirvana.user.rnr.fp.dao.FpRnrSmsInfoDao;
import com.cusc.nirvana.user.rnr.fp.dao.entity.FpRnrSmsInfoPO;
import com.cusc.nirvana.user.rnr.fp.dto.FpRnrSmsInfoDTO;
import com.cusc.nirvana.user.rnr.fp.service.IFpRnrSmsInfoService;
import com.cusc.nirvana.user.rnr.mg.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.util.Date;
import java.util.List;
/**
* 实名业务短信信息(FpRnrSmsInfo)表服务实现类
*
* @author yuy336
* @since 2022-04-19 20:39:07
*/
@Service
public class FpRnrSmsInfoServiceImpl extends ServiceImpl<FpRnrSmsInfoDao, FpRnrSmsInfoPO>
implements IFpRnrSmsInfoService {
/**
* 通过UUID查询单条数据
*
* @param bean
* @return 实例对象
*/
@Override
public FpRnrSmsInfoDTO getByUuid(FpRnrSmsInfoDTO bean) {
FpRnrSmsInfoPO record = this.getPoByUuid(bean.getUuid());
return FpRnrSmsInfoConverter.INSTANCE.poToDto(record);
}
@Override
public FpRnrSmsInfoDTO getPoByMessageId(FpRnrSmsInfoDTO bean) {
return FpRnrSmsInfoConverter.INSTANCE.poToDto(getOnetByMessageId(bean.getSendSmsId()));
}
/**
* 通过查询条件查询集合数据
*
* @param bean
* @return 集合对象
*/
@Override
public List<FpRnrSmsInfoDTO> queryByList(FpRnrSmsInfoDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.orderByDesc("create_time");
queryWrapper.eq(CuscStringUtils.isNotEmpty(bean.getSendSmsId()), "send_sms_id", bean.getSendSmsId());
queryWrapper.eq(bean.getBizType() != null, "biz_type", bean.getBizType());
queryWrapper.eq(CuscStringUtils.isNotEmpty(bean.getRnrId()), "rnr_id", bean.getRnrId());
List<FpRnrSmsInfoPO> record = this.list(queryWrapper);
return FpRnrSmsInfoConverter.INSTANCE.poListToDtoList(record);
}
/**
* 根据orderid查短信信息
*
* @param bean 筛选条件
* @return 查询结果
*/
@Override
public List<FpRnrSmsInfoDTO> queryByOrderId(FpRnrSmsInfoDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("order_id",bean.getOrderId());
queryWrapper.orderByDesc("create_time");
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
List<FpRnrSmsInfoPO> list = this.list(queryWrapper);
return FpRnrSmsInfoConverter.INSTANCE.poListToDtoList(list);
}
/**
* 分页查询
*
* @param bean 筛选条件
* @return 查询结果
*/
@Override
public PageResult<FpRnrSmsInfoDTO> queryByPage(FpRnrSmsInfoDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.orderByDesc("create_time");
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
Page<FpRnrSmsInfoPO> page =
this.page(new Page<>(bean.getCurrPage(), bean.getPageSize()), queryWrapper);
return PageHelper.convert(page, FpRnrSmsInfoDTO.class);
}
/**
* 新增数据
*
* @param bean 实例对象
* @return 实例对象
*/
@Override
@Transactional
public FpRnrSmsInfoDTO insert(FpRnrSmsInfoDTO bean) {
//发送短信
//保存记录
FpRnrSmsInfoPO fpRnrSmsInfoPO = FpRnrSmsInfoConverter.INSTANCE.dtoToPo(bean);
fpRnrSmsInfoPO.setUuid(CuscStringUtils.generateUuid());
fpRnrSmsInfoPO.setCreateTime(new Date());
this.save(fpRnrSmsInfoPO);
bean.setUuid(fpRnrSmsInfoPO.getUuid());
return bean;
}
/**
* 修改数据
*
* @param bean 实例对象
* @return 实例对象
*/
@Override
@Transactional
public FpRnrSmsInfoDTO update(FpRnrSmsInfoDTO bean) {
FpRnrSmsInfoPO fpRnrSmsInfoPO = this.getPoByUuid(bean.getUuid());
if (fpRnrSmsInfoPO == null) {
return null;
}
FpRnrSmsInfoPO tmpBean = FpRnrSmsInfoConverter.INSTANCE.dtoToPo(bean);
tmpBean.setId(fpRnrSmsInfoPO.getId());
this.updateById(tmpBean);
return bean;
}
/**
* 短信回调后更新短信状态
*
* @param bean
* @return
*/
@Override
public FpRnrSmsInfoDTO getPoByPhoneNo(FpRnrSmsInfoDTO bean) {
QueryWrapper<FpRnrSmsInfoPO> queryWrapper = new QueryWrapper();
queryWrapper.orderByDesc("create_time");
queryWrapper.eq("send_phone", bean.getSendPhone());
queryWrapper.eq("is_delete", 0);
queryWrapper.eq(!StringUtils.isEmpty(bean.getSendSmsId()),"send_sms_id", bean.getSendSmsId());
List<FpRnrSmsInfoPO> list = this.list(queryWrapper);
if (!CollectionUtils.isEmpty(list)) {
return FpRnrSmsInfoConverter.INSTANCE.poToDto(list.get(0));
}
return null;
}
/**
* 通过主键删除数据
*
* @param bean 实例对象
* @return 是否成功
*/
@Override
@Transactional
public boolean deleteById(FpRnrSmsInfoDTO bean) {
FpRnrSmsInfoPO fpRnrSmsInfoPO = this.getPoByUuid(bean.getUuid());
if (fpRnrSmsInfoPO == null) {
return false;
}
FpRnrSmsInfoPO tmpBean = new FpRnrSmsInfoPO();
tmpBean.setId(fpRnrSmsInfoPO.getId());
tmpBean.setIsDelete(CommonDeleteEnum.DELETED.getCode());
return this.updateById(tmpBean);
}
/**
* 通过UUID查询单条数据
*
* @param uuid
* @return 实例对象
*/
private FpRnrSmsInfoPO getPoByUuid(String uuid) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", uuid);
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
return this.getOne(queryWrapper);
}
/**
* 通过mssageId查询多条数据
*
* @param mssageId
* @return 实例对象
*/
private FpRnrSmsInfoPO getOnetByMessageId(String mssageId) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("send_sms_id", mssageId);
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
return this.getOne(queryWrapper);
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.alibaba.fastjson.JSON;
import com.cusc.nirvana.common.result.PageResult;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.eiam.client.OrganizationClient;
import com.cusc.nirvana.user.eiam.dto.OrganizationDTO;
import com.cusc.nirvana.user.rnr.fp.service.IFpSearchCardAuthService;
import com.cusc.nirvana.user.rnr.mg.client.*;
import com.cusc.nirvana.user.rnr.mg.constants.CommonYesOrNoEnum;
import com.cusc.nirvana.user.rnr.mg.dto.*;
import com.cusc.nirvana.user.util.crypt.CryptKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* @modify hxin 2022-05-18
*
*/
@Service
@Slf4j
public class FpSearchCardAuthServiceImpl implements IFpSearchCardAuthService {
@Resource
private MgRnrCardInfoClient cardInfoClient;
@Resource
private MgRnrInfoClient infoClient;
@Resource
private MgRnrCompanyInfoClient companyInfoClient;
@Resource
private RnrOrderClient orderClient;
@Resource
private MgRnrLiaisonInfoClient liaisonInfoClient;
@Resource
private OrganizationClient organizationClient;
@Resource
private MgCheckProgressClient mgCheckProgressClient;
/**
* 单车进度查询 重构返回对象
* @param dto
* @return
*/
@Override
public Response<List<MgSearchCardAuthDTO>> getMgSearchCardAuthDTO(MgRnrCardInfoDTO dto){
log.info("fp获取单车审核进度入参cardInfo: {}", JSON.toJSONString(dto));
List<MgRnrCardInfoDTO> cards = getCards(dto);
log.info("fp获取单车审核进度出参cardInfo: {}", JSON.toJSONString(cards));
if(CollectionUtils.isEmpty(cards)){
return Response.createError("该vin查不到任何卡信息");
}
List<MgSearchCardAuthDTO> searchCardAuthDTOS = new ArrayList<>();
for(MgRnrCardInfoDTO cardInfoDTO : cards){
MgSearchCardAuthDTO mgSearchCardAuthDTO = new MgSearchCardAuthDTO();
//MgRnrCardInfoDTO cardInfoDTO = cards.get(i);
mgSearchCardAuthDTO.setCardInfoDTO(cardInfoDTO);
//查order信息
RnrOrderDTO orderDTO = new RnrOrderDTO();
orderDTO.setUuid(cardInfoDTO.getOrderId());
RnrOrderDTO order = getOrder(orderDTO);
log.info("fp获取单车审核进度order出参: {}", JSON.toJSONString(order));
mgSearchCardAuthDTO.setRnrOrderDTO(order);
//查rnrinfo 实名信息
MgRnrInfoDTO rnrInfoDTO = new MgRnrInfoDTO();
rnrInfoDTO.setUuid(cardInfoDTO.getRnrId());
MgRnrInfoDTO rnrInfo = getRnrInfo(rnrInfoDTO);
log.info("fp获取单车审核进度rnrinfo出参: {}", JSON.toJSONString(rnrInfo));
mgSearchCardAuthDTO.setRnrInfoDTO(rnrInfo);
if(rnrInfo != null){
if(rnrInfo.getIsCompany().equals(CommonYesOrNoEnum.YES.getCode())){ //若是企业实名查企业信息 魔法值重构?
MgRnrCompanyInfoDTO companyInfoDTO = new MgRnrCompanyInfoDTO();
companyInfoDTO.setRnrId(rnrInfo.getUuid());
MgRnrCompanyInfoDTO company = getCompany(companyInfoDTO);
log.info("fp获取单车审核进度companyInfo出参: {}", JSON.toJSONString(company));
mgSearchCardAuthDTO.setCompanyInfoDTO(company);
}
//和委托实名暂无关系
// if(rnrInfo.getIsTrust().equals("1")){
// MgRnrLiaisonInfoDTO liaisonInfoDTO = new MgRnrLiaisonInfoDTO();
// liaisonInfoDTO.setRnrId(rnrInfo.getUuid());
// MgRnrLiaisonInfoDTO liaison = getLiaison(liaisonInfoDTO);
// mgSearchCardAuthDTO.setLiaisonInfoDTO(liaison);
// }
//查询经销商信息
if(StringUtils.isNotEmpty(rnrInfo.getOrgId())){
OrganizationDTO organizationDTO = getOrganizationDTO(rnrInfo.getOrgId());
mgSearchCardAuthDTO.setOrgName(organizationDTO.getOrganName());
}
}
searchCardAuthDTOS.add(mgSearchCardAuthDTO);
}
return Response.createSuccess(searchCardAuthDTOS);
}
@Override
public Response<PageResult<MgCheckProgressDTO>> getMgCheckProgress(MgCheckProgressDTO param) {
Response<PageResult<MgCheckProgressDTO>> pageResultResponse = mgCheckProgressClient.queryByPage(param);
//可能需要调别的服务查询经销商信息、审核人信息
List<MgCheckProgressDTO> list = pageResultResponse.getData().getList();
list.forEach( mgCheckProgressDTO -> {
// if(StringUtils.isNotBlank(mgCheckProgressDTO.getStartCheckDate())){
// mgCheckProgressDTO.setStartCheckDate(mgCheckProgressDTO.getStartCheckDate().substring(0,10));
// }
// if(StringUtils.isNotBlank(mgCheckProgressDTO.getEndCheckDate())){
// mgCheckProgressDTO.setEndCheckDate(mgCheckProgressDTO.getEndCheckDate().substring(0,10));
// }
//敏感信息解密
mgCheckProgressDTO.setFullName(CryptKeyUtil.decryptByBase64(mgCheckProgressDTO.getFullName()));
mgCheckProgressDTO.setPhone(CryptKeyUtil.decryptByBase64(mgCheckProgressDTO.getPhone()));
mgCheckProgressDTO.setCompanyName(CryptKeyUtil.decryptByBase64(mgCheckProgressDTO.getCompanyName()));
//经销商信息
if(StringUtils.isNotBlank(mgCheckProgressDTO.getOrgId())){
OrganizationDTO organizationDTO = getOrganizationDTO(mgCheckProgressDTO.getOrgId());
mgCheckProgressDTO.setOrgName(organizationDTO.getOrganName());
}
});
return pageResultResponse;
}
/**********************************私有方法区********************************************/
/**
* 获取cardlist
*/
public List<MgRnrCardInfoDTO> getCards(MgRnrCardInfoDTO dto){
Response<List<MgRnrCardInfoDTO>> listResponse = cardInfoClient.queryByList(dto);
if(!listResponse.isSuccess()){
return null;
}
return listResponse.getData();
}
/**
* 获取rnrinfo
* @param dto
* @return
*/
public MgRnrInfoDTO getRnrInfo(MgRnrInfoDTO dto){
Response<MgRnrInfoDTO> byUuid = infoClient.getByUuid(dto);
if(!byUuid.isSuccess()){
return new MgRnrInfoDTO();
}
return byUuid.getData();
}
/**
* 获取rnrinfo
* @param dto
* @return
*/
public RnrOrderDTO getOrder(RnrOrderDTO dto){
Response<RnrOrderDTO> byUuid = orderClient.getByUuid(dto);
if(!byUuid.isSuccess()){
return new RnrOrderDTO();
}
return byUuid.getData();
}
/**
* 获取公司信息
* @param dto
* @return
*/
public MgRnrCompanyInfoDTO getCompany(MgRnrCompanyInfoDTO dto){
Response<MgRnrCompanyInfoDTO> byRnrid = companyInfoClient.getByRnrid(dto);
if(!byRnrid.isSuccess()){
return new MgRnrCompanyInfoDTO();
}
return byRnrid.getData();
}
/**
* 获取代办人信息
* @param dto
* @return
*/
public MgRnrLiaisonInfoDTO getLiaison(MgRnrLiaisonInfoDTO dto){
Response<MgRnrLiaisonInfoDTO> byRnrid = liaisonInfoClient.getByRnrid(dto);
if(!byRnrid.isSuccess()){
return null;
}
return byRnrid.getData();
}
/**
* 获取组织信息
* @param orgId
* @return
*/
private OrganizationDTO getOrganizationDTO(String orgId) {
OrganizationDTO organizationDTO = new OrganizationDTO();
organizationDTO.setUuid(orgId);
Response<OrganizationDTO> byUuid = organizationClient.getByUuid(organizationDTO);
if (byUuid.isSuccess()){
return byUuid.getData();
}else{
return organizationDTO;
}
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cusc.nirvana.common.result.BaseEnum;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.rnr.fp.constants.BizTypeEnum;
import com.cusc.nirvana.user.rnr.fp.dao.entity.FpRnrSmsInfoPO;
import com.cusc.nirvana.user.rnr.fp.dto.*;
import com.cusc.nirvana.user.rnr.fp.service.IFpRnrSmsInfoService;
import com.cusc.nirvana.user.rnr.fp.service.IFpSurplusCardBindService;
import com.cusc.nirvana.user.rnr.fp.service.IRnrService;
import com.cusc.nirvana.user.rnr.fp.service.ShortMessageCheckService;
import com.cusc.nirvana.user.rnr.mg.client.MgSurplusBindClient;
import com.cusc.nirvana.user.rnr.mg.client.RnrOrderClient;
import com.cusc.nirvana.user.rnr.mg.constants.NoticeStatusEnum;
import com.cusc.nirvana.user.rnr.mg.constants.RnrOrderStatusEnum;
import com.cusc.nirvana.user.rnr.mg.constants.RnrStatus;
import com.cusc.nirvana.user.rnr.mg.dto.RnrOrderDTO;
import com.cusc.nirvana.user.rnr.mg.dto.RnrRelationDTO;
import com.cusc.nirvana.user.rnr.mg.dto.SurplusConfirmDto;
import com.cusc.nirvana.user.util.CuscStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author yubo
* @since 2022-05-03 17:01
*/
@Service
@Slf4j
public class FpSurplusCardBindServiceImpl implements IFpSurplusCardBindService {
@Autowired
MgSurplusBindClient surplusBindClient;
@Autowired
ShortMessageCheckService messageCheckService;
@Autowired
private IFpRnrSmsInfoService smsInfoService;
@Autowired
private IRnrService rnrService;
@Autowired
private RnrOrderClient orderClient;
@Value("${message.callback.timeout:120}")
private int timeOut;
/**
* 一车多卡绑定
*
* @param dto
* @return
*/
@Override
public Response surplusCardBind(RnrRelationDTO dto) {
rnrService.cardNumberCheck(dto);
dto.getCardList().forEach(card -> {
card.setRnrStatus(RnrStatus.INIT.getCode());
card.setNoticeStatus(NoticeStatusEnum.NONEED.getCode());
});
Response response = surplusBindClient.saveSurplusRnrRelation(dto);
if (!response.isSuccess()) {
throw new CuscUserException(response.getCode(), response.getMsg());
}
//发送短信
response = sendMessage(dto);
if (!response.isSuccess()) {
throw new CuscUserException(response.getCode(), response.getMsg());
}
return Response.createSuccess(BaseEnum.SUCCESS.getMsg(), dto.getOrder().getUuid());
}
/**
* 一车多卡绑定 不发短信 默认确认以及工单状态也默认通过
*
* @param dto
* @return
*/
@Override
public Response surplusCardBindDirect(RnrRelationDTO dto) {
rnrService.cardNumberCheck(dto);
dto.getCardList().forEach(card -> {
card.setRnrStatus(RnrStatus.INIT.getCode());
card.setNoticeStatus(NoticeStatusEnum.NONEED.getCode());
});
Response response = surplusBindClient.saveSurplusRnrRelation(dto);
if (!response.isSuccess()) {
throw new CuscUserException(response.getCode(), response.getMsg());
}
return Response.createSuccess(BaseEnum.SUCCESS.getMsg(), dto.getOrder().getUuid());
}
/**
* 短信回调
*
* @param dto
* @return
*/
@Override
public Boolean confirm(SurplusConfirmDto dto) {
Response<Boolean> booleanResponse = surplusBindClient.surplusConfirm(dto);
if (!booleanResponse.isSuccess()) {
throw new CuscUserException(booleanResponse.getCode(), booleanResponse.getMsg());
}
return true;
}
/**
* 查询结果
*
* @param bean
* @return
*/
@Override
public SurplusQueryResponseDTO queryResult(SurplusQueryRequestDTO bean) {
SurplusQueryResponseDTO responseDTO = new SurplusQueryResponseDTO();
long currentTimeMillis = System.currentTimeMillis();
//查询工单信息
RnrOrderDTO rnrOrderDTO = new RnrOrderDTO();
rnrOrderDTO.setUuid(bean.getOrderId());
Response<RnrOrderDTO> byUuid = orderClient.getByUuid(rnrOrderDTO);
if (!byUuid.isSuccess() || byUuid.getData() == null) {
throw new CuscUserException("", "查询工单信息失败:" + byUuid.getMsg());
}
//
rnrOrderDTO = byUuid.getData();
if (!RnrOrderStatusEnum.notFinished(rnrOrderDTO.getOrderStatus())) {
responseDTO.setOrderId(rnrOrderDTO.getUuid());
responseDTO.setOrderStatus(rnrOrderDTO.getOrderStatus());
return responseDTO;
}
//查询短信信息
QueryWrapper<FpRnrSmsInfoPO> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("order_id", bean.getOrderId());
queryWrapper.orderByDesc("create_time");
List<FpRnrSmsInfoPO> list = smsInfoService.list(queryWrapper);
if (CollectionUtils.isEmpty(list)) {
throw new CuscUserException("", "获取短信信息失败");
}
//校验时间
long time = list.get(0).getCreateTime().getTime();
log.info("判断超时,{},{},{},{}", currentTimeMillis, timeOut, time, currentTimeMillis - timeOut * 1000);
if (currentTimeMillis - timeOut * 1000 > time) {
log.info("短信回复超时,设置成失败状态");
throw new CuscUserException("", "回复短信超时");
// SurplusConfirmDto confirmDto = new SurplusConfirmDto();
// confirmDto.setOrderId(bean.getOrderId());
// confirmDto.setCallbackStatusEnum(MessageCallbackStatusEnum.TIMEOUT.getCode());
// Response<Boolean> response = surplusBindClient.surplusConfirm(confirmDto);
// if (!response.isSuccess()) {
// throw new CuscUserException(response.getCode(), "回复短信超时:" + response.getMsg());
// }
//
// //重新获取工单状态
// rnrOrderDTO.setUuid(bean.getOrderId());
// byUuid = orderClient.getByUuid(rnrOrderDTO);
// if (!byUuid.isSuccess() || byUuid.getData() == null) {
// throw new CuscUserException("", "查询工单信息失败:" + byUuid.getMsg());
// }
// responseDTO.setOrderId(byUuid.getData().getUuid());
// responseDTO.setOrderStatus(byUuid.getData().getOrderStatus());
// return responseDTO;
} else {
//未超时直接返回状态
responseDTO.setOrderId(rnrOrderDTO.getUuid());
responseDTO.setOrderStatus(rnrOrderDTO.getOrderStatus());
return responseDTO;
}
}
/**
* 发送短信
*
* @param relationDTO
*/
@Override
@Transactional
public Response sendMessage(RnrRelationDTO relationDTO) {
SmsRequestDTO smsRequestDTO = toSmsRequestDto(relationDTO);
//短信入库
FpRnrSmsInfoDTO fpRnrSmsInfoDTO = new FpRnrSmsInfoDTO();
fpRnrSmsInfoDTO.setIsDelete(0);
fpRnrSmsInfoDTO.setCreateTime(new Date(System.currentTimeMillis()));
fpRnrSmsInfoDTO.setUuid(CuscStringUtils.generateUuid());
fpRnrSmsInfoDTO.setSendPhone(smsRequestDTO.getPhone());
fpRnrSmsInfoDTO.setRnrId(relationDTO.getInfo().getUuid());
fpRnrSmsInfoDTO.setOrderId(relationDTO.getOrder().getUuid());
fpRnrSmsInfoDTO.setIccids(relationDTO.getCardList().stream().map(c -> c.getIccid())
.collect(Collectors.joining(",")));
fpRnrSmsInfoDTO.setSendContent(smsRequestDTO.getParams().toString());
fpRnrSmsInfoDTO.setBizType(MessageBizTypeEnum.BIND.getCode());
fpRnrSmsInfoDTO.setCreator(relationDTO.getInfo().getCreator());
fpRnrSmsInfoDTO.setOperator(relationDTO.getInfo().getCreator());
//发送短信
Response<SmsResponseDTO> response = messageCheckService.sendSms(smsRequestDTO);
if (!response.isSuccess()) {
throw new CuscUserException(response.getCode(), response.getMsg());
}
fpRnrSmsInfoDTO.setSendSmsId(response.getData().getMessageId());
smsInfoService.insert(fpRnrSmsInfoDTO);
return Response.createSuccess();
}
//------------------------------------- 私有方法区域
//短信消息
private SmsRequestDTO toSmsRequestDto(RnrRelationDTO dto) {
SmsRequestDTO smsRequestDTO = new SmsRequestDTO();
smsRequestDTO.setTenantNo(dto.getOrder().getTenantNo());
smsRequestDTO.setBizType(BizTypeEnum.BIND.getCode());
smsRequestDTO.setPhone(dto.getInfo().getPhone());
//短信参数
List<String> params = new ArrayList<>();
params.add(dto.getInfo().getFullName() + "女士/先生");
params.add(dto.getCardList().get(0).getIotId());
params.add(dto.getCardList().stream().map(c -> c.getIccid()).collect(Collectors.joining(",")));
smsRequestDTO.setParams(params);
return smsRequestDTO;
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cache.CacheFactory;
import com.cache.exception.CacheException;
import com.cusc.nirvana.common.loader.CollectionUtils;
import com.cusc.nirvana.common.loader.StringUtils;
import com.cusc.nirvana.common.result.PageResult;
import com.cusc.nirvana.rds.mybatis.PageHelper;
import com.cusc.nirvana.user.rnr.fp.constants.CryptKeyHelper;
import com.cusc.nirvana.user.rnr.fp.converter.FpCarInfoConverter;
import com.cusc.nirvana.user.rnr.fp.converter.FpT1UploadStatusConverter;
import com.cusc.nirvana.user.rnr.fp.dao.FpT1UploadStatusDao;
import com.cusc.nirvana.user.rnr.fp.dao.entity.FpT1UploadStatusPO;
import com.cusc.nirvana.user.rnr.fp.dto.FpCarInfoDTO;
import com.cusc.nirvana.user.rnr.fp.dto.FpT1UploadStatusDTO;
import com.cusc.nirvana.user.rnr.fp.service.IFpT1UploadStatusService;
import com.cusc.nirvana.user.util.CuscStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
/**
* T1上报状态(FpT1UploadStatus)表服务实现类
*
* @author yuy336
* @since 2022-07-06 14:12:22
*/
@Service
@Slf4j
public class FpT1UploadStatusServiceImpl extends ServiceImpl<FpT1UploadStatusDao, FpT1UploadStatusPO>
implements IFpT1UploadStatusService {
@Resource
private CacheFactory cacheFactory;
/**
* 通过UUID查询单条数据
*
* @param bean
* @return 实例对象
*/
@Override
public FpT1UploadStatusDTO getByUuid(FpT1UploadStatusDTO bean) {
FpT1UploadStatusPO record = this.getPoByUuid(bean.getUuid());
return FpT1UploadStatusConverter.INSTANCE.poToDto(record);
}
/**
* 通过查询条件查询集合数据
*
* @param bean
* @return 集合对象
*/
@Override
public List<FpT1UploadStatusDTO> queryByList(FpT1UploadStatusDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("iccid", CryptKeyHelper.encrypt(bean.getIccid()));
queryWrapper.eq("order_id", bean.getOrderId());
queryWrapper.eq(StringUtils.isNotBlank(bean.getTenantNo()), "tenant_no", bean.getTenantNo());
queryWrapper.orderByDesc("create_time");
List<FpT1UploadStatusPO> record = this.list(queryWrapper);
return FpT1UploadStatusConverter.INSTANCE.poListToDtoList(record);
}
/**
* 分页查询
*
* @param bean 筛选条件
* @return 查询结果
*/
@Override
public PageResult<FpT1UploadStatusDTO> queryByPage(FpT1UploadStatusDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.orderByDesc("create_time");
Page<FpT1UploadStatusPO> page =
this.page(new Page<>(bean.getCurrPage(), bean.getPageSize()), queryWrapper);
return PageHelper.convert(page, FpT1UploadStatusDTO.class);
}
/**
* 新增数据
*
* @param bean 实例对象
* @return 实例对象
*/
@Override
@Transactional
public FpT1UploadStatusDTO insert(FpT1UploadStatusDTO bean) {
FpT1UploadStatusPO fpT1UploadStatusPO = FpT1UploadStatusConverter.INSTANCE.dtoToPo(bean);
// fpT1UploadStatusPO.setUuid(CuscStringUtils.generateUuid());
this.save(fpT1UploadStatusPO);
bean.setUuid(fpT1UploadStatusPO.getUuid());
return bean;
}
/**
* 修改数据
*
* @param bean 实例对象
* @return 实例对象
*/
@Override
@Transactional
public FpT1UploadStatusDTO update(FpT1UploadStatusDTO bean) {
FpT1UploadStatusPO fpT1UploadStatusPO = this.getPoByUuid(bean.getUuid());
if (fpT1UploadStatusPO == null) {
return null;
}
FpT1UploadStatusPO tmpBean = FpT1UploadStatusConverter.INSTANCE.dtoToPo(bean);
tmpBean.setId(fpT1UploadStatusPO.getId());
this.updateById(tmpBean);
return bean;
}
@Override
@Transactional
public boolean clearDataByIccid(FpT1UploadStatusDTO bean) {
baseMapper.clearDataByIccid(bean);
return true;
}
@Override
public boolean clearFlowDataByIccid(FpT1UploadStatusDTO bean) {
baseMapper.clearFlowDataByIccid(bean);
return true;
}
/**
* 通过主键删除数据
*
* @param bean 实例对象
* @return 是否成功
*/
@Override
@Transactional
public boolean deleteById(FpT1UploadStatusDTO bean) {
FpT1UploadStatusPO fpT1UploadStatusPO = this.getPoByUuid(bean.getUuid());
if (fpT1UploadStatusPO == null) {
return false;
}
return this.removeById(fpT1UploadStatusPO.getId());
}
@Override
@Transactional
public FpT1UploadStatusDTO insertOrReset(FpT1UploadStatusDTO bean) {
//String lockKey = RedisConstant.T1_UPLOAD_STATUS_LOCK + bean.getIccid() + "_" + bean.getOrderId();
//try {
// Boolean lock = cacheFactory.getLockService().lock(lockKey, RedisConstant.T1_UPLOAD_STATUS_LOCK_EXPIRE);
// if (!lock) {
// return null;
// }
//} catch (CacheException e) {
// log.error("insertOrReset 加锁失败 : ", e);
//}
FpT1UploadStatusDTO queryBean = new FpT1UploadStatusDTO();
queryBean.setIccid(bean.getIccid());
queryBean.setOrderId(bean.getOrderId());
queryBean.setTenantNo(bean.getTenantNo());
List<FpT1UploadStatusDTO> t1UploadStatusList = queryByList(bean);
FpT1UploadStatusDTO ret;
if (CollectionUtils.isEmpty(t1UploadStatusList)) {
bean.setUuid(CuscStringUtils.generateUuid());
ret = insert(bean);
} else {
ret = bean;
ret.setUuid(t1UploadStatusList.get(0).getUuid());
clearDataByIccid(ret);
}
//unlockKey(lockKey);
return ret;
}
@Override
public FpT1UploadStatusDTO insertOrResetFlow(FpT1UploadStatusDTO bean) {
FpT1UploadStatusDTO queryBean = new FpT1UploadStatusDTO();
queryBean.setIccid(bean.getIccid());
queryBean.setOrderId(bean.getOrderId());
queryBean.setTenantNo(bean.getTenantNo());
List<FpT1UploadStatusDTO> t1UploadStatusList = queryByList(bean);
FpT1UploadStatusDTO ret;
if (CollectionUtils.isEmpty(t1UploadStatusList)) {
bean.setUuid(CuscStringUtils.generateUuid());
ret = insert(bean);
} else {
ret = bean;
ret.setUuid(t1UploadStatusList.get(0).getUuid());
clearFlowDataByIccid(ret);
}
return ret;
}
@Override
public FpT1UploadStatusDTO getByIccidAndOrderId(String iccid, String orderId) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("iccid", CryptKeyHelper.encrypt(iccid));
queryWrapper.eq("order_id", orderId);
queryWrapper.orderByDesc("create_time");
List<FpT1UploadStatusPO> record = this.list(queryWrapper);
if (CollectionUtils.isEmpty(record)) {
return null;
}
return FpT1UploadStatusConverter.INSTANCE.poToDto(record.get(0));
}
@Override
public FpT1UploadStatusDTO getByRequestId(String requestId) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("request_id", requestId);
queryWrapper.orderByDesc("create_time");
List<FpT1UploadStatusPO> record = this.list(queryWrapper);
if (CollectionUtils.isEmpty(record)) {
return null;
}
return FpT1UploadStatusConverter.INSTANCE.poToDto(record.get(0));
}
@Override
public List<FpT1UploadStatusDTO> queryByRequestIdList(List<String> requestIdList) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.in("request_id", requestIdList);
queryWrapper.eq("user_status",1);
queryWrapper.eq("file_status",1);
queryWrapper.ne("report_completion",1);
queryWrapper.orderByDesc("create_time");
List<FpT1UploadStatusPO> record = this.list(queryWrapper);
if (CollectionUtils.isEmpty(record)) {
return null;
}
return FpT1UploadStatusConverter.INSTANCE.poListToDtoList(record);
}
/**
* 通过UUID查询单条数据
*
* @param uuid
* @return 实例对象
*/
private FpT1UploadStatusPO getPoByUuid(String uuid) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", uuid);
return this.getOne(queryWrapper);
}
/**
* 释放redis锁
*
* @param lockKey key
*/
private void unlockKey(String lockKey) {
try {
cacheFactory.getLockService().unLock(lockKey);
} catch (CacheException e) {
log.error("Failed to unlock " + lockKey + " ", e);
}
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cusc.nirvana.common.result.PageResult;
import com.cusc.nirvana.rds.mybatis.PageHelper;
import com.cusc.nirvana.user.rnr.fp.converter.FpUserOperationLogConverter;
import com.cusc.nirvana.user.rnr.fp.dao.FpUserOperationLogDao;
import com.cusc.nirvana.user.rnr.fp.dao.entity.FpUserOperationLogPO;
import com.cusc.nirvana.user.rnr.fp.dto.FpUserOperationLogDTO;
import com.cusc.nirvana.user.rnr.fp.service.IFpUserOperationLogService;
import com.cusc.nirvana.user.rnr.mg.constants.CommonDeleteEnum;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 用户操作日志(FpUserOperationLog)表服务实现类
*
* @author yuy336
* @since 2022-06-20 09:38:35
*/
@Service
public class FpUserOperationLogServiceImpl extends ServiceImpl<FpUserOperationLogDao, FpUserOperationLogPO> implements IFpUserOperationLogService {
/**
* 通过UUID查询单条数据
*
* @param bean
* @return 实例对象
*/
@Override
public FpUserOperationLogDTO getByUuid(FpUserOperationLogDTO bean) {
FpUserOperationLogPO record = this.getPoByUuid(bean.getUuid());;
return FpUserOperationLogConverter.INSTANCE.poToDto(record);
}
/**
* 通过查询条件查询集合数据
*
* @param bean
* @return 集合对象
*/
@Override
public List<FpUserOperationLogDTO> queryByList(FpUserOperationLogDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
queryWrapper.orderByDesc("create_time");
List<FpUserOperationLogPO> record = this.list(queryWrapper);
return FpUserOperationLogConverter.INSTANCE.poListToDtoList(record);
}
/**
* 分页查询
*
* @param bean 筛选条件
* @return 查询结果
*/
@Override
public PageResult<FpUserOperationLogDTO> queryByPage(FpUserOperationLogDTO bean) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.orderByDesc("create_time");
queryWrapper.eq("org_id",bean.getOrgId());
queryWrapper.isNotNull("creator");
queryWrapper.eq(CuscStringUtils.isNotEmpty(bean.getCreator()),"creator",bean.getCreator());
queryWrapper.eq(CuscStringUtils.isNotEmpty(bean.getOptModule()),"opt_module",bean.getOptModule());
queryWrapper.eq(CuscStringUtils.isNotEmpty(bean.getOptAction()),"opt_action",bean.getOptAction());
queryWrapper.gt(null != bean.getCreateTimeQueryStart(),"create_time",bean.getCreateTimeQueryStart());
queryWrapper.lt(null != bean.getCreateTimeQueryStartEnd(),"create_time",bean.getCreateTimeQueryStartEnd());
Page<FpUserOperationLogPO> page =
this.page(new Page<>(bean.getCurrPage(), bean.getPageSize()), queryWrapper);
return PageHelper.convert(page, FpUserOperationLogDTO.class);
}
/**
* 新增数据
*
* @param bean 实例对象
* @return 实例对象
*/
@Override
@Transactional
public FpUserOperationLogDTO insert(FpUserOperationLogDTO bean) {
FpUserOperationLogPO fpUserOperationLogPO = FpUserOperationLogConverter.INSTANCE.dtoToPo(bean);
fpUserOperationLogPO.setUuid(CuscStringUtils.generateUuid());
this.save(fpUserOperationLogPO);
bean.setUuid(fpUserOperationLogPO.getUuid());
return bean;
}
/**
* 修改数据
*
* @param bean 实例对象
* @return 实例对象
*/
@Override
@Transactional
public FpUserOperationLogDTO update(FpUserOperationLogDTO bean) {
FpUserOperationLogPO fpUserOperationLogPO = this.getPoByUuid(bean.getUuid());
if(fpUserOperationLogPO == null){
return null;
}
FpUserOperationLogPO tmpBean = FpUserOperationLogConverter.INSTANCE.dtoToPo(bean);
tmpBean.setId(fpUserOperationLogPO.getId());
this.updateById(tmpBean);
return bean;
}
/**
* 通过主键删除数据
* @param bean 实例对象
* @return 是否成功
*/
@Override
@Transactional
public boolean deleteById(FpUserOperationLogDTO bean) {
FpUserOperationLogPO fpUserOperationLogPO = this.getPoByUuid(bean.getUuid());
if (fpUserOperationLogPO == null) {
return false;
}
FpUserOperationLogPO tmpBean = new FpUserOperationLogPO();
tmpBean.setId(fpUserOperationLogPO.getId());
return this.updateById(tmpBean);
}
/**
* 通过UUID查询单条数据
*
* @param uuid
* @return 实例对象
*/
private FpUserOperationLogPO getPoByUuid(String uuid) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("uuid", uuid);
queryWrapper.eq("is_delete", CommonDeleteEnum.NORMAL.getCode());
return this.getOne(queryWrapper);
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cusc.nirvana.user.rnr.fp.constants.UploadStatus;
import com.cusc.nirvana.user.rnr.fp.constants.UploadType;
import com.cusc.nirvana.user.rnr.fp.dao.InstructionLogDao;
import com.cusc.nirvana.user.rnr.fp.dao.entity.InstructionLogPO;
import com.cusc.nirvana.user.rnr.fp.dao.entity.InstructionPO;
import com.cusc.nirvana.user.rnr.fp.service.IInstructionLogService;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.springframework.stereotype.Service;
@Service
public class InstructionLogServiceImpl extends ServiceImpl<InstructionLogDao, InstructionLogPO> implements IInstructionLogService {
@Override
public InstructionLogPO insertLog(InstructionPO instructionPO, UploadType uploadType, UploadStatus status) {
InstructionLogPO instructionLogPO = new InstructionLogPO();
instructionLogPO.setUuid(CuscStringUtils.generateUuid());
instructionLogPO.setRequestId(instructionPO.getRequestId());
instructionLogPO.setIccid(instructionPO.getIccid());
instructionLogPO.setUploadType(uploadType.getCode());
instructionLogPO.setStatus(UploadStatus.Success == status ? UploadStatus.Success.getCode() : UploadStatus.Failed.getCode());
baseMapper.insert(instructionLogPO);
return instructionLogPO;
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cache.CacheFactory;
import com.cache.exception.CacheException;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.rnr.fp.common.MbCodeEnum;
import com.cusc.nirvana.user.rnr.fp.common.config.EncryptionConfig;
import com.cusc.nirvana.user.rnr.fp.constants.RedisConstant;
import com.cusc.nirvana.user.rnr.fp.constants.UploadStatus;
import com.cusc.nirvana.user.rnr.fp.constants.UploadType;
import com.cusc.nirvana.user.rnr.fp.converter.InstructionConverter;
import com.cusc.nirvana.user.rnr.fp.dao.InstructionDao;
import com.cusc.nirvana.user.rnr.fp.dao.entity.InstructionPO;
import com.cusc.nirvana.user.rnr.fp.dto.*;
import com.cusc.nirvana.user.rnr.fp.service.*;
import com.cusc.nirvana.user.rnr.fp.util.CuscFileUtils;
import com.cusc.nirvana.user.rnr.fp.util.Md5CaculateUtil;
import com.cusc.nirvana.user.rnr.fp.util.RnrDataAesUtil;
import com.cusc.nirvana.user.rnr.fp.util.ZipUtils;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrCardInfoClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrFileClient;
import com.cusc.nirvana.user.rnr.mg.client.OrgSimRelClient;
import com.cusc.nirvana.user.rnr.mg.constants.RnrFileType;
import com.cusc.nirvana.user.rnr.mg.constants.RnrStatus;
import com.cusc.nirvana.user.rnr.mg.dto.IccIdListRequestDTO;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrCardInfoDTO;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrFileDTO;
import com.cusc.nirvana.user.rnr.mg.dto.OrgSimRelDTO;
import com.cusc.nirvana.user.util.CuscStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.io.*;
import java.util.Iterator;
import java.util.List;
/**
* 执行上传实现类
*/
@Slf4j
@Service
@EnableScheduling
@RefreshScope
public class InstructionServiceImpl extends ServiceImpl<InstructionDao, InstructionPO> implements IInstructionService {
@Value("${T1.instruction.retry.maxAttempts:10}")
private int maxAttempts;
@Value("${T1.instruction.retry.lock.expireTime:3600}")
private int expireTime;
@Value("${t1.vehicle.t1InstructionKey:}")
//此接口上传的车辆信息加密密钥由工信部下发
private String t1InstructionKey;
@Resource
private IInstructionLogService iInstructionLogService;
@Resource
private CacheFactory cacheFactory;
@Autowired
private MgRnrCardInfoClient rnrCardInfoClient;
@Autowired
@Qualifier("noBalanceRestTemplateRnrFp")
RestTemplate noBalanceRestTemplateRnrFp;
@Autowired
private IFileService fileService;
@Autowired
private MgRnrFileClient rnrFileClient;
// @Autowired
// private IFpT1VehicleCompanyService t1VehicleCompanyService;
@Autowired
private ChinaMobileT1UploadServiceImpl chinaMobileT1UploadService;
@Autowired
private ChinaUnicomT1UploadServiceImpl chinaUnicomT1UploadService;
@Autowired
private ChinaTelecomT1UploadServiceImpl chinaTelecomT1UploadServiceImpl;
@Autowired
private OrgSimRelClient orgSimRelClient;
@Autowired
private EncryptionConfig encryptionConfig;
@Autowired
private CtccT1UploadService ctccSftpUtil;
@Autowired
private CmccT1UploadService cmccSftpUtil;
@Autowired
private OperatorService operatorService;
@Autowired
private IT1UploadService it1UploadService;;
/**
* 定时任务,从数据库中获取未完成上报的指令,进行上报
*/
@Scheduled(fixedRateString = "${T1.instruction.retry.interval:300000}")
public void uploadTask() {
findFailedJobAndUpload();
}
/**
* 接受上报指令,进行上报
*
* @param instructionDTO 上报信息
* @return 上报结果
*/
@Override
public InstructionRespDTO uploadInfo(InstructionDTO instructionDTO) {
String requestId = instructionDTO.getRequestID();
String iccid = instructionDTO.getICCID();
if (StringUtils.isBlank(requestId)) {
return InstructionRespDTO.createError(requestId, "指令标识缺失");
}
if (StringUtils.isBlank(iccid)) {
return InstructionRespDTO.createError(requestId, "ICCID缺失");
}
//直接保存到指令库
InstructionPO infoPO = insertInstruction(instructionDTO);
//异步方式上报一次
asyncUploadInfo(infoPO);
//返回成功状态,表示接收到了指令并插入指令库
return InstructionRespDTO.createSuccess(requestId);
}
@Override
public InstructionRespDTO instructionsIssue(InstructionDTO instructionDTO) {
String requestId = instructionDTO.getRequestID();
String iccid = instructionDTO.getICCID();
if (StringUtils.isBlank(requestId)) {
return InstructionRespDTO.createError(requestId, "指令标识缺失");
}
if (StringUtils.isBlank(iccid)) {
return InstructionRespDTO.createError(requestId, "ICCID缺失");
}
//直接保存到指令库
InstructionPO infoPO = insertInstruction(instructionDTO);
//异步方式上报一次
asyncUploadInfoIssue(infoPO);
//返回成功状态,表示接收到了指令并插入指令库
return InstructionRespDTO.createSuccess(requestId);
}
/**
* 异步方式上报指令信息
*
* @param instructionPO 指令信息
*/
@Override
@Async("uploadExecutor")
public void asyncUploadInfo(InstructionPO instructionPO) {
tryUploadInfo(instructionPO.getUuid());
}
@Async("uploadIssueExecutor")
public void asyncUploadInfoIssue(InstructionPO instructionPO) {
tryUploadInfoIssue(instructionPO.getUuid());
}
@Override
public InstructionPO getByUuid(String uuid) {
QueryWrapper<InstructionPO> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("uuid", uuid);
return this.getOne(queryWrapper);
}
/**
* 发送超过重试次数告警信息
*
* @param instructionPO 指令信息
*/
@Override
public void sendWarningMessage(InstructionPO instructionPO) {
log.warn("Send warning info, iccid:" + instructionPO.getIccid());
//发送告警信息
}
/**
* 插入指令信息
*
* @param instructionDTO 指令信息
*/
@Override
public InstructionPO insertInstruction(InstructionDTO instructionDTO) {
InstructionPO instructionPO = InstructionConverter.INSTANCE.dtoToPo(instructionDTO);
instructionPO.setUuid(CuscStringUtils.generateUuid());
this.save(instructionPO);
return instructionPO;
}
/**
* 重试上报 指令通道只需要上报文件:入网合同
*
* @param uuid 指令业务主键
*/
@Override
public void tryUploadInfo(String uuid) {
String lockKey = RedisConstant.RNR_INSTRUCTION_UPLOAD_KEY + uuid;
try {
//根据业务主键加锁,多个fp服务可以同时上报不同的指令
Boolean lock = cacheFactory.getLockService().lock(lockKey, expireTime);
if (!lock) {
return;
}
//获取最新状态,以免其他fp服务已经上报成功
InstructionPO instructionPO = getByUuid(uuid);
if (uploadFailed(instructionPO) && instructionPO.getRetryCount() < maxAttempts) {
//有信息没有上报成功并且没有超过最大尝试次数
boolean allSuccess = true;
instructionPO.setRetryCount(instructionPO.getRetryCount() + 1);
//调用照片类信息上传
if (!uploadFinished(instructionPO.getFileUploadStatus())) {
allSuccess = doUpload(instructionPO, UploadType.File, (requestId, code, iccid) -> {
//通过iccid查询实名的记录
MgRnrCardInfoDTO card = new MgRnrCardInfoDTO();
card.setIccid(iccid);
card.setRnrStatus(RnrStatus.RNR.getCode());
Response<List<MgRnrCardInfoDTO>> cardListResp = rnrCardInfoClient.queryByList(card);
if (!cardListResp.isSuccess() || CollectionUtils.isEmpty(cardListResp.getData())) {
log.error("tryUploadInfo 指令上报-通过卡查询卡列表失败, 原因:{}", JSON.toJSONString(cardListResp));
return false;
}
card = cardListResp.getData().get(0);
//查询入网合同
MgRnrFileDTO rnrFileDTO = new MgRnrFileDTO();
rnrFileDTO.setRnrId(card.getRnrId());
rnrFileDTO.setTenantNo(card.getTenantNo());
rnrFileDTO.setFileType(RnrFileType.VEHUCLE_BIND.getCode());
Response<List<MgRnrFileDTO>> rnrFileResp = rnrFileClient.queryByList(rnrFileDTO);
if (!rnrFileResp.isSuccess() || CollectionUtils.isEmpty(rnrFileResp.getData())) {
log.error("tryUploadInfo 指令上报-查询文件失败, 原因:{}", JSON.toJSONString(rnrFileResp));
return false;
}
//通过code 查询指令上报密钥
/*FpT1VehicleCompanyDTO t1VehicleCompanyDTO = new FpT1VehicleCompanyDTO();
t1VehicleCompanyDTO.setCompanyCode(code);
t1VehicleCompanyDTO = t1VehicleCompanyService.getByCode(t1VehicleCompanyDTO);*/
EncryptionKeyDTO encryptionKeyDTO = encryptionConfig.getKey(card.getOrderId());
// final FpT1VehicleCompanyDTO t1VehicleCompanyDTO = getFpT1VehicleCompanyDTO(iccid);
if (encryptionKeyDTO == null || encryptionKeyDTO.getT1InstructionKey() == null) {
log.error("tryUploadInfo 指令上报-通过code查询密钥失败,code:{}", code);
return false;
}
//调用照片类信息上传
T1FileReqDTO t1FileReqDTO = new T1FileReqDTO();
t1FileReqDTO.setCode(code);
t1FileReqDTO.setRequestID(requestId);
return fileUploadInstruction(rnrFileResp.getData(), t1FileReqDTO,
encryptionKeyDTO, iccid);
});
}
if (!allSuccess && instructionPO.getRetryCount() >= maxAttempts) {
sendWarningMessage(instructionPO);
}
}
} catch (Exception e) {
log.error("RetryUploadInfo failed, uuid:" + uuid, e);
} finally {
unlockKey(lockKey);
}
}
public void tryUploadInfoIssue(String uuid) {
String lockKey = RedisConstant.RNR_INSTRUCTION_UPLOAD_KEY + uuid;
try {
//根据业务主键加锁,多个fp服务可以同时上报不同的指令
Boolean lock = cacheFactory.getLockService().lock(lockKey, expireTime);
if (!lock) {
return;
}
//获取最新状态,以免其他fp服务已经上报成功
InstructionPO instructionPO = getByUuid(uuid);
if (uploadFailed(instructionPO) && instructionPO.getRetryCount() < maxAttempts) {
//有信息没有上报成功并且没有超过最大尝试次数
boolean allSuccess = true;
instructionPO.setRetryCount(instructionPO.getRetryCount() + 1);
//调用照片类信息上传
if (!uploadFinished(instructionPO.getFileUploadStatus())) {
allSuccess = doUpload(instructionPO, UploadType.File, (requestId, code, iccid) -> {
Response<OrgSimRelDTO> response =orgSimRelClient.getByIccid(iccid);
if(!response.isSuccess()||null ==response.getData()){
log.error("没有查询到卡信息,iccid为{}",instructionPO.getIccid());
return false;
}
//通过iccid查询实名的记录
MgRnrCardInfoDTO card = new MgRnrCardInfoDTO();
card.setIccid(iccid);
card.setRnrStatus(RnrStatus.RNR.getCode());
Response<List<MgRnrCardInfoDTO>> cardListResp = rnrCardInfoClient.queryByList(card);
if (!cardListResp.isSuccess() || CollectionUtils.isEmpty(cardListResp.getData())) {
log.error("tryUploadInfo 指令上报-通过卡查询卡列表失败, 原因:{}", JSON.toJSONString(cardListResp));
return false;
}
card = cardListResp.getData().get(0);
//查询入网合同
MgRnrFileDTO rnrFileDTO = new MgRnrFileDTO();
rnrFileDTO.setRnrId(card.getRnrId());
rnrFileDTO.setTenantNo(card.getTenantNo());
rnrFileDTO.setFileType(RnrFileType.VEHUCLE_BIND.getCode());
Response<List<MgRnrFileDTO>> rnrFileResp = rnrFileClient.queryByList(rnrFileDTO);
if (!rnrFileResp.isSuccess() || CollectionUtils.isEmpty(rnrFileResp.getData())) {
log.error("tryUploadInfo 指令上报-查询文件失败, 原因:{}", JSON.toJSONString(rnrFileResp));
return false;
}
//通过code 查询指令上报密钥
/*FpT1VehicleCompanyDTO t1VehicleCompanyDTO = new FpT1VehicleCompanyDTO();
t1VehicleCompanyDTO.setCompanyCode(code);
t1VehicleCompanyDTO = t1VehicleCompanyService.getByCode(t1VehicleCompanyDTO);*/
EncryptionKeyDTO encryptionKeyDTO = encryptionConfig.getKey(response.getData().getOrgUuid());
// final FpT1VehicleCompanyDTO t1VehicleCompanyDTO = getFpT1VehicleCompanyDTO(iccid);
if (encryptionKeyDTO == null || encryptionKeyDTO.getT1InstructionKey() == null) {
log.error("tryUploadInfo 指令上报-通过code查询密钥失败,code:{}", code);
return false;
}
//调用照片类信息上传
T1FileReqDTO t1FileReqDTO = new T1FileReqDTO();
t1FileReqDTO.setCode(encryptionKeyDTO.getCompanyCode());
t1FileReqDTO.setRequestID(requestId);
t1FileReqDTO.setPlatformID(encryptionKeyDTO.getPlatFormId());
return fileUploadInstruction(rnrFileResp.getData(), t1FileReqDTO,
encryptionKeyDTO, iccid);
});
}
if (!allSuccess && instructionPO.getRetryCount() >= maxAttempts) {
sendWarningMessage(instructionPO);
}
}
} catch (Exception e) {
log.error("RetryUploadInfo failed, uuid:" + uuid, e);
} finally {
unlockKey(lockKey);
}
}
//-------------------私有方法区-------------------
/**
* Description: 获取联通,电信,移动等信息
* <br />
* CreateDate 2022-06-15 09:50:30
*
* @author zx
**/
private final FpT1VehicleCompanyDTO getFpT1VehicleCompanyDTO(String iccid) {
final FpT1VehicleCompanyDTO fpT1VehicleCompanyDTO = new FpT1VehicleCompanyDTO();
final MbCodeEnum mbCodeEnum = MbCodeEnum.get(iccid);
switch (mbCodeEnum) {
case CMCC:
fpT1VehicleCompanyDTO.setCompanyCode(chinaMobileT1UploadService.getCode());
fpT1VehicleCompanyDTO.setT1UserInfoKey(chinaMobileT1UploadService.getT1UserInfoKey());
fpT1VehicleCompanyDTO.setT1InstructionKey(t1InstructionKey);
break;
case CUCC:
fpT1VehicleCompanyDTO.setCompanyCode(chinaUnicomT1UploadService.getCode());
fpT1VehicleCompanyDTO.setT1UserInfoKey(chinaUnicomT1UploadService.getT1UserInfoKey());
fpT1VehicleCompanyDTO.setT1InstructionKey(t1InstructionKey);
break;
case CTCC:
fpT1VehicleCompanyDTO.setCompanyCode(chinaTelecomT1UploadServiceImpl.getCode());
fpT1VehicleCompanyDTO.setT1UserInfoKey(chinaTelecomT1UploadServiceImpl.getT1UserInfoKey());
fpT1VehicleCompanyDTO.setT1InstructionKey(t1InstructionKey);
break;
}
return fpT1VehicleCompanyDTO;
}
/**
* Description: 文件信息上报
* <br />
* CreateDate 2022-06-08 09:50:30
*
* @author yuyi
**/
private boolean fileUploadInstruction(List<MgRnrFileDTO> list, T1FileReqDTO t1FileReqDTO, EncryptionKeyDTO encryptionKeyDTO, String iccid) {
//从文件系统下载文件到本地目录
String folderName = "HT_" + t1FileReqDTO.getRequestID() + "_" + t1FileReqDTO.getCode();
String folderPath = System.getProperty("java.io.tmpdir") + File.separator + folderName;
File rootFile = new File(folderPath);
if (!rootFile.exists()) {
rootFile.mkdirs();
}
FileDownloadDTO fileDownload;
StringBuffer sbr;
for (int i = 0; i < list.size(); i++) {
sbr = new StringBuffer(folderName);
sbr.append("_");
sbr.append(String.format("%03d", i+1)) ;
/*//通过文件id查询文件格式
FileRecordDTO fileRecord = fileService.fileMetainfo(list.get(i).getFileSystemId());
if (fileRecord == null) {
log.error("文件【{}】未查询到文件信息", list.get(i).getFileSystemId());
continue;
}*/
//增加文件类型后缀
final String fileSystemId = list.get(i).getFileSystemId();
sbr.append(fileSystemId.substring(fileSystemId.lastIndexOf(".")));
fileDownload = new FileDownloadDTO();
fileDownload.setFilePath(folderPath);
fileDownload.setUuid(fileSystemId);
fileDownload.setFileName(sbr.toString());
//fileService.downloadToLocal(fileDownload);
try {
byte[] bytes = fileService.downLoadBytes(fileSystemId);
FileUtils.writeByteArrayToFile(
new File(fileDownload.getFilePath() + File.separator + fileDownload.getFileName()),
bytes);
} catch (IOException e) {
log.error("FileUtils.writeByteArrayToFile error ", e);
}
}
//压缩目录并加密,将压缩文件读取到EncryptFile中
String zipFileName = folderPath + ".zip";
try {
if (com.cusc.nirvana.user.rnr.fp.constants.MbCodeEnum.CMCC.getCode().equals(operatorService.get(iccid))) {
ZipUtils.toZip(folderPath, new FileOutputStream(zipFileName), false);
File file = it1UploadService.encryptZipFile(new File(zipFileName),encryptionKeyDTO);
t1FileReqDTO.setEncryptFile(file);
cmccSftpUtil.upload(t1FileReqDTO);
return true;
}else {
ZipUtils.toZip(folderPath, new FileOutputStream(zipFileName), false);
//移动,联通,电信加密算法不同
final File file = encryptZipFile(iccid, zipFileName, folderPath);
t1FileReqDTO.setEncryptFile(file);
final T1CommonResponseDTO t1CommonResponseDTO = uploadInstructionT1File(t1FileReqDTO, iccid);
return true;
}
} catch (Exception e) {
log.error("ZipUtils toZip error ", e);
return false;
} finally {
//删除文件夹
CuscFileUtils.delFolder(folderPath);
//删除zip文件
File zipFile = new File(zipFileName);
if (zipFile.exists()) {
zipFile.delete();
}
//删除bin文件
File binFile = new File(folderPath + ".bin");
if (binFile.exists()) {
binFile.delete();
}
}
}
private final File encryptZipFile(String iccid, String zipFileName, String folderPath) {
final MbCodeEnum mbCodeEnum = MbCodeEnum.get(iccid);
switch (mbCodeEnum) {
case CMCC:
return chinaMobileT1UploadService.encryptZipFile(zipFileName, folderPath);
case CUCC:
return chinaUnicomT1UploadService.encryptZipFile(zipFileName, folderPath);
case CTCC:
return chinaTelecomT1UploadServiceImpl.encryptZipFile(zipFileName, folderPath);
default:
return null;
}
}
/**
* Description: 上传开户信息
* <br />
* CreateDate 2022-05-16 10:22:07
*
* @author yuyi
**/
private T1CommonResponseDTO uploadInstructionT1File(T1FileReqDTO file, String iccid) {
final MbCodeEnum mbCodeEnum = MbCodeEnum.get(iccid);
switch (mbCodeEnum) {
case CMCC:
return chinaMobileT1UploadService.uploadT1FileByInstruction(file);
case CUCC:
return chinaUnicomT1UploadService.uploadT1File(file);
case CTCC:
return chinaTelecomT1UploadServiceImpl.uploadT1File(file);
default:
return null;
}
}
/**
* 更新上传状态,并插入日志
*
* @param instructionPO
* @param uploadType
* @param status
*/
private void uploadStatusAndSaveLog(InstructionPO instructionPO, UploadType uploadType, UploadStatus status) {
switch (uploadType) {
case File:
instructionPO.setFileUploadStatus(status.getCode());
break;
case User:
instructionPO.setUserUploadStatus(status.getCode());
break;
case Vehicle:
instructionPO.setVehicleUploadStatus(status.getCode());
break;
default:
break;
}
baseMapper.updateById(instructionPO);
iInstructionLogService.insertLog(instructionPO, uploadType, status);
}
/**
* 上传信息
*
* @param instructionPO 指令信息
* @param uploadType 上传类型
* @param handler 上报执行方式
*/
private boolean doUpload(InstructionPO instructionPO, UploadType uploadType, UploadHandler handler) {
if (handler.upload(instructionPO.getRequestId(), instructionPO.getCode(), instructionPO.getIccid())) {
uploadStatusAndSaveLog(instructionPO, uploadType, UploadStatus.Success);
return true;
} else {
uploadStatusAndSaveLog(instructionPO, uploadType, UploadStatus.Failed);
return false;
}
}
/**
* 判断是有信息没有上传成功
*/
private boolean uploadFailed(InstructionPO instructionPO) {
return !uploadFinished(instructionPO.getUserUploadStatus()) || !uploadFinished(
instructionPO.getFileUploadStatus());
}
/**
* 释放redis锁
*
* @param lockKey key
*/
private void unlockKey(String lockKey) {
try {
cacheFactory.getLockService().unLock(lockKey);
} catch (CacheException e) {
log.error("Failed to unlock " + lockKey, e);
}
}
/**
* 查询所有失败并且未到最大重试次数的请求,按照请求先后顺序进行重试
*/
private void findFailedJobAndUpload() {
Iterator<InstructionPO> its = findFailedAndRetryableInstructions();
while (its.hasNext()) {
InstructionPO next = its.next();
tryUploadInfo(next.getUuid());
}
}
/**
* 是否已经上传成功
*
* @param status 上报状态
*/
private boolean uploadFinished(Integer status) {
return status != null && status == 1;
}
/**
* @return 未完成指令迭代器
*/
private Iterator<InstructionPO> findFailedAndRetryableInstructions() {
return new Iterator<InstructionPO>() {
private Page<InstructionPO> instructions;
int currentPage = 1;
int currentIndex = 0;
@Override
public boolean hasNext() {
if (instructions != null && currentIndex < instructions.getRecords().size()) {
return true;
}
if (instructions == null) {
instructions = findNexPage(currentPage++);
currentIndex = 0;
} else if (currentIndex >= instructions.getRecords().size()) {
currentIndex = 0;
if (instructions.hasNext()) {
instructions = findNexPage(currentPage++);
} else {
instructions = null;
}
}
return instructions != null && !instructions.getRecords().isEmpty();
}
@Override
public InstructionPO next() {
return instructions.getRecords().get(currentIndex++);
}
};
}
/**
* 分页查询数据
* 查询 1.上报失败并且没有超过重试次数的执行
*
* @param page 当前页
* @return 页数据
*/
private Page<InstructionPO> findNexPage(int page) {
QueryWrapper<InstructionPO> queryWrapper = new QueryWrapper<>();
//retry_count < maxAttempts
// and (user_upload_status != 1 or vehicle_upload_status !=1 or file_upload_status !=1)
queryWrapper.lt("retry_count", maxAttempts);
queryWrapper.and(wrapper -> wrapper.ne("file_upload_status", 1));
queryWrapper.orderByAsc("create_time");
return this.page(new Page<>(page, 100), queryWrapper);
}
/**
* 上报处理类
*
* @author yubo
* @since 2022-04-15 10:41
*/
private interface UploadHandler {
//处理上报信息
boolean upload(String requestId, String code, String iccid);
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.alibaba.fastjson.JSON;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.rnr.fp.common.ResponseCode;
import com.cusc.nirvana.user.rnr.fp.dto.FpRnrSmsInfoDTO;
import com.cusc.nirvana.user.rnr.fp.dto.UnbindReceiceSMSDTO;
import com.cusc.nirvana.user.rnr.fp.handler.MessageCallBackContext;
import com.cusc.nirvana.user.rnr.fp.handler.MessageCallbackHandler;
import com.cusc.nirvana.user.rnr.fp.service.IFpCardUnBindService;
import com.cusc.nirvana.user.rnr.fp.service.IMessageCallBackService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author yubo
* @since 2022-05-06 16:36
*/
@Service
@Slf4j
public class MessageCallBackServiceImpl implements IMessageCallBackService {
@Autowired
IFpCardUnBindService cardUnBindService;
@Autowired
private MessageCallBackContext messageCallBackContext;
@Override
public Response callBack(UnbindReceiceSMSDTO bean) {
log.info("短信平台回调入参: {}", JSON.toJSONString(bean));
long receiveTIme = System.currentTimeMillis();
//获取当前时间 校验时间合法 校验短信内容
FpRnrSmsInfoDTO smsInfoDTO = new FpRnrSmsInfoDTO();
smsInfoDTO.setSendPhone(bean.getPhoneNumber());
smsInfoDTO.setSendSmsId(bean.getMessageId());
Response response = this.checkMessageStatus(smsInfoDTO);
if (!response.isSuccess()) {
return Response.createError(response.getMsg(), response.getData());
}
//存储短信信息
Response<FpRnrSmsInfoDTO> fpRnrSmsInfoDTOResponse = cardUnBindService.receiveMessage(bean);
if (!fpRnrSmsInfoDTOResponse.isSuccess() || fpRnrSmsInfoDTOResponse.getData() == null) {
return Response.createError("短信回调失败", response.getData());
}
FpRnrSmsInfoDTO rnrSmsInfoDTOResponseData = fpRnrSmsInfoDTOResponse.getData();
MessageCallbackHandler workBackHandler = messageCallBackContext.getWorkBackHandler(rnrSmsInfoDTOResponseData.getBizType());
if (workBackHandler != null) {
return workBackHandler.callBack(rnrSmsInfoDTOResponseData, bean, receiveTIme);
} else {
log.error("未找到指定的消息回调处理类{}", rnrSmsInfoDTOResponseData.getBizType());
return Response.createError("未找到指定的消息回调处理类");
}
}
//校验短信状态
private Response checkMessageStatus(FpRnrSmsInfoDTO bean) {
log.info("自然人解绑校验短信入参: {}", JSON.toJSONString(bean));
Response<FpRnrSmsInfoDTO> messageStatus = cardUnBindService.getMessageStatus(bean);
if (!messageStatus.isSuccess()) {
return Response.createError(messageStatus.getMsg(), messageStatus.getCode());
}
if (messageStatus.getData() == null) {
return Response.createError("获取上行短信消息失败", ResponseCode.INVALID_DATA.getCode());
}
if (StringUtils.isNotBlank(messageStatus.getData().getReceiveContent())) {
return Response.createError("上行短信消息已处理", ResponseCode.INVALID_DATA.getCode());
}
return Response.createSuccess("短信状态有效");
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSONObject;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.rnr.fp.common.ResponseCode;
import com.cusc.nirvana.user.rnr.fp.common.constant.VinCardCheckBussinessDetailType;
import com.cusc.nirvana.user.rnr.fp.dto.*;
import com.cusc.nirvana.user.rnr.fp.handler.VinCardCheckMessageHandler;
import com.cusc.nirvana.user.rnr.fp.service.IFileService;
import com.cusc.nirvana.user.rnr.fp.service.INewVinCardService;
import com.cusc.nirvana.user.rnr.fp.service.ISimVehicleRelService;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrCardInfoClient;
import com.cusc.nirvana.user.rnr.mg.client.MgRnrInfoClient;
import com.cusc.nirvana.user.rnr.mg.client.RnrOrderClient;
import com.cusc.nirvana.user.rnr.mg.constants.RnrOrderStatusEnum;
import com.cusc.nirvana.user.rnr.mg.constants.RnrOrderType;
import com.cusc.nirvana.user.rnr.mg.constants.RnrStatus;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrCardInfoDTO;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrInfoDTO;
import com.cusc.nirvana.user.rnr.mg.dto.RnrOrderDTO;
import com.cusc.nirvana.user.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author stayAnd
* @date 2022/5/17
*/
@Service
@Slf4j
public class NewVinCardServiceImpl implements INewVinCardService {
@Resource
private MgRnrCardInfoClient cardInfoClient;
@Resource
private ISimVehicleRelService simVehicleRelService;
@Resource
private MgRnrInfoClient rnrInfoClient;
@Resource
private IFileService fileService;
@Resource
private RnrOrderClient orderClient;
private static final Integer BATCH_CHECK_SIZE = 500;
/**
* 新改造的方法
*/
@Override
public Response<VinCardResultDTO> queryUnBindCardByVin(VinCardQueryDTO queryDTO) {
VinCardResultDTO resultDTO = new VinCardResultDTO();
resultDTO.setVin(queryDTO.getVin());
//根据vin获取iccid卡列表
Response<List<VinIccidDTO>> iccidResponse = null;
try {
iccidResponse = simVehicleRelService.getIccidByVin(queryDTO.getVin());
log.info("根据vin查询iccid列表,vin = {} ,response = {}",queryDTO.getVin(),JSONObject.toJSONString(iccidResponse));
} catch (Exception e) {
log.info("根据vin查询iccid列表出错,vin = {}",queryDTO.getVin(),e);
resultDTO.setIccidList(Collections.emptyList());
//return Response.createError("根据vin查询iccid列表出错");
return Response.createSuccess(resultDTO);
}
if (null == iccidResponse || !iccidResponse.isSuccess() || CollectionUtils.isEmpty(iccidResponse.getData())) {
resultDTO.setIccidList(Collections.emptyList());
return Response.createSuccess(resultDTO);
}
List<VinIccidDTO> iccidDTOList = iccidResponse.getData();
List<String> iccidList = iccidDTOList.stream().map(VinIccidDTO::getIccid).collect(Collectors.toList());
MgRnrCardInfoDTO cardQuery = new MgRnrCardInfoDTO();
cardQuery.setIccidList(iccidList);
List<MgRnrCardInfoDTO> cardInfoList = cardInfoClient.queryByList(cardQuery).getData();
//非一车多卡时 过滤掉车企业实名的卡
if (!Boolean.TRUE.equals(queryDTO.getFilter())) {
cardInfoList = filterManufacturerRnr(cardInfoList);
}
List<String> rnrCardList = cardInfoList.stream().filter(card -> RnrStatus.INIT.getCode() == card.getRnrStatus() || RnrStatus.RNR.getCode() == card.getRnrStatus())
.map(MgRnrCardInfoDTO::getIccid).collect(Collectors.toList());
// 过滤掉已实名/初始化状态的iccid
List<String> filterIccidList = iccidList.stream().filter(iccId -> !rnrCardList.contains(iccId)).collect(Collectors.toList());
resultDTO.setIccidList(filterIccidList);
log.info("查询返回的iccid是,{}",iccidList);
log.info("已实名/初始化状态iccid是,{}",rnrCardList);
log.info("通过vin查询车卡关系表,当前未实名的iccid是,{}",filterIccidList);
return Response.createSuccess(resultDTO);
}
@Override
public VinCardResultDTO queryBindCardByVin(VinCardQueryDTO queryDTO) {
MgRnrCardInfoDTO query = new MgRnrCardInfoDTO();
query.setIotId(queryDTO.getVin());
Response<List<MgRnrCardInfoDTO>> response = cardInfoClient.queryByList(query);
VinCardResultDTO resultDTO = new VinCardResultDTO();
resultDTO.setVin(queryDTO.getVin());
if (null == response || !response.isSuccess() || CollectionUtils.isEmpty(response.getData())) {
resultDTO.setIccidList(Collections.emptyList());
return resultDTO;
}
List<MgRnrCardInfoDTO> cardList = response.getData();
String rnrId = cardList.get(0).getRnrId();
resultDTO.setRnrId(rnrId);
List<String> iccidList = cardList.stream().filter(
card->card.getRnrStatus() == RnrStatus.INIT.getCode()
|| card.getRnrStatus() == RnrStatus.RNR.getCode()
).map(MgRnrCardInfoDTO::getIccid).collect(Collectors.toList());
//添加去重
iccidList = iccidList.stream().distinct().collect(Collectors.toList());
log.info("查询实名卡信息表,有实名记录的是,{}", iccidList);
resultDTO.setIccidList(iccidList);
return resultDTO;
}
@Override
public VinCardCheckResultDTO checkVinCard(VinCardCheckDTO vinCardCheckDTO) {
log.info("checkVinCard 检查卡信息:{}",JSONObject.toJSONString(vinCardCheckDTO));
Integer businessType = vinCardCheckDTO.getBusinessType();
if (VinCardCheckBussinessDetailType.NATURALPERSON_NEW.getType().equals(businessType) || VinCardCheckBussinessDetailType.ONECAR_MORECARD.getType().equals(businessType)) {
//自然人实名-新车主 || 一车多卡绑定
return checkNewNeedBindCard(vinCardCheckDTO.getVin(),vinCardCheckDTO.getIccidList(),VinCardCheckBussinessDetailType.getBytype(businessType));
} else if (VinCardCheckBussinessDetailType.NATURALPERSON_SECOND.getType().equals(businessType)) {
//自然人实名-二手车新车主
checkNeedUnBindCard(vinCardCheckDTO.getVin(),vinCardCheckDTO.getIccidList(),vinCardCheckDTO.getRnrId(),VinCardCheckBussinessDetailType.NATURALPERSON_SECOND);
} else if (VinCardCheckBussinessDetailType.ENTERPRISE.getType().equals(businessType) || VinCardCheckBussinessDetailType.VEHICLE.getType().equals(businessType)){
//企业实名 || 车企实名
processExcel(vinCardCheckDTO,VinCardCheckBussinessDetailType.getBytype(businessType));
} else if (VinCardCheckBussinessDetailType.UNBIND_ORIGINAL.getType().equals(businessType) || VinCardCheckBussinessDetailType.UNBIND_SECOND.getType().equals(businessType)){
//卡解绑 - 原车主 || 卡解绑 - 二手车解绑
return checkNeedUnBindCard(vinCardCheckDTO.getVin(),vinCardCheckDTO.getIccidList(),vinCardCheckDTO.getRnrId(),VinCardCheckBussinessDetailType.getBytype(businessType));
} else if (VinCardCheckBussinessDetailType.CHANGE_BOX.getType().equals(businessType)){
//换件
if (!CollectionUtils.isEmpty(vinCardCheckDTO.getIccidList())) {
//老卡
checkNeedUnBindCard(vinCardCheckDTO.getVin(),vinCardCheckDTO.getIccidList(),vinCardCheckDTO.getRnrId(),VinCardCheckBussinessDetailType.CHANGE_BOX);
}
if (!CollectionUtils.isEmpty(vinCardCheckDTO.getNewIccidList())) {
//新卡
checkNewNeedBindCard(vinCardCheckDTO.getVin(),vinCardCheckDTO.getNewIccidList(),VinCardCheckBussinessDetailType.CHANGE_BOX);
}
} else if (VinCardCheckBussinessDetailType.UNBIND_VEHICLE.getType().equals(businessType)){
//车企实名解绑
processExcel(vinCardCheckDTO,VinCardCheckBussinessDetailType.UNBIND_VEHICLE);
}
return null;
}
private void processExcel(VinCardCheckDTO vinCardCheckDTO, VinCardCheckBussinessDetailType bussinessDetailType) {
String fileId = vinCardCheckDTO.getFileId();
if (StringUtils.isBlank(fileId)){
throw new CuscUserException("","文件信息为空");
}
byte[] bytes = fileService.downLoadBytes(fileId);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
List<VinCardExcelData> excelList = new ArrayList<>();
EasyExcel.read(inputStream, VinCardExcelData.class, new AnalysisEventListener<VinCardExcelData>() {
@Override
public void invoke(VinCardExcelData vinCardExcelData, AnalysisContext analysisContext) {
excelList.add(vinCardExcelData);
if (excelList.size() >= BATCH_CHECK_SIZE) {
processExcelData(excelList,bussinessDetailType);
excelList.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
if (!CollectionUtils.isEmpty(excelList)) {
processExcelData(excelList,bussinessDetailType);
}
}
}).sheet().doRead();
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void processExcelData(List<VinCardExcelData> excelList, VinCardCheckBussinessDetailType detailType) {
log.info("processExcelData excelList = {}",JSONObject.toJSONString(excelList));
Map<String, List<VinCardExcelData>> map = excelList.stream().collect(Collectors.groupingBy(VinCardExcelData::getVin));
map.entrySet().parallelStream().forEach(entry->{
String vin = entry.getKey();
List<VinCardExcelData> excelDataList = entry.getValue();
List<String> iccidList = excelDataList.stream().map(VinCardExcelData::getIccid).collect(Collectors.toList());
if (detailType.equals(VinCardCheckBussinessDetailType.UNBIND_VEHICLE)) {
//车企实名解绑
checkNeedUnBindCard(vin,iccidList,null,VinCardCheckBussinessDetailType.UNBIND_VEHICLE);
} else {
//企业实名 车企实名
checkNewNeedBindCard(vin,iccidList,detailType);
}
});
}
/**
* 校验需要新解绑的卡
* @param vin
* @param iccidList
* @param rnrId
* @param detailType
* @return
*/
private VinCardCheckResultDTO checkNeedUnBindCard(String vin,List<String> iccidList,String rnrId,VinCardCheckBussinessDetailType detailType) {
//输入的卡必须是 已经实名的记录
List<MgRnrCardInfoDTO> cardInfoDTOList = queryCardListByIccidList(iccidList);
List<String> hasRnrIccidList = cardInfoDTOList.stream()
.filter(card -> RnrStatus.RNR.getCode() == card.getRnrStatus()).map(MgRnrCardInfoDTO::getIccid)
.collect(Collectors.toList());
if (!hasRnrIccidList.containsAll(iccidList)) {
log.error("或者存在实名过,但是实名状态是初始化的情况");
throw new CuscUserException("", "输入的卡信息存在非实名的卡");
}
if (cardInfoDTOList.stream().filter(card->RnrStatus.RNR.getCode() == card.getRnrStatus()).anyMatch(card->StringUtils.isNotBlank(card.getIotId()) && !card.getIotId().equals(vin))){
throw new CuscUserException("", "输入的卡信息存在vin和输入的vin不一致");
}
//检查 要解绑的卡是否存在未完成的工单信息
checkUnFinishOrder(cardInfoDTOList);
if (detailType.getType().equals(VinCardCheckBussinessDetailType.UNBIND_ORIGINAL.getType()) || detailType.getType().equals(VinCardCheckBussinessDetailType.CHANGE_BOX.getType())) {
rnrId = StringUtils.isBlank(rnrId) ? cardInfoDTOList.get(0).getRnrId():rnrId;
MgRnrInfoDTO query = new MgRnrInfoDTO();
query.setUuid(rnrId);
MgRnrInfoDTO rnrInfoDTO = rnrInfoClient.getByUuid(query).getData();
if (null == rnrInfoDTO) {
throw new CuscUserException("","未查询到实名信息,rnrId:"+rnrId);
}
return new VinCardCheckResultDTO().setName(rnrInfoDTO.getFullName()).setPhone(rnrInfoDTO.getPhone());
}
return null;
}
private void checkUnFinishOrder(List<MgRnrCardInfoDTO> iccidList) {
List<String> orderIdList = iccidList.stream().map(MgRnrCardInfoDTO::getOrderId).distinct().collect(Collectors.toList());
List<String> notFinishOrderIdList = orderIdList.parallelStream().filter(orderId -> {
RnrOrderDTO query = new RnrOrderDTO();
query.setUuid(orderId);
RnrOrderDTO orderDTO = orderClient.getByUuid(query).getData();
return RnrOrderStatusEnum.notFinished(orderDTO.getOrderStatus());
}).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(notFinishOrderIdList)) {
throw new CuscUserException("", "存在未完成的工单信息");
}
}
/**
* 校验需要新绑定的卡
* @param vin
* @param iccidList
* @param detailType
*/
private VinCardCheckResultDTO checkNewNeedBindCard(String vin,List<String> iccidList,VinCardCheckBussinessDetailType detailType) {
//查询卡是否存在
checkCardExsit(iccidList);
//查询车卡关系
checkVinCardRelation(iccidList,vin);
//查询vin是否存在已实名/初始化(认证中)的记录
List<MgRnrCardInfoDTO> mgRnrCardInfoList = queryCardListByVin(vin);
//输入的卡是否存在 已实名/初始化(认证中)的记录
List<MgRnrCardInfoDTO> cardInfoDTOList = queryCardListByIccidList(iccidList);
//新车 企业实名需要过滤掉车企实名的卡
if(detailType.getType().equals(VinCardCheckBussinessDetailType.NATURALPERSON_NEW.getType())
|| detailType.getType().equals(VinCardCheckBussinessDetailType.ENTERPRISE.getType())) {
mgRnrCardInfoList = filterManufacturerRnr(mgRnrCardInfoList);
cardInfoDTOList = filterManufacturerRnr(cardInfoDTOList);
}
if (cardInfoDTOList.stream().anyMatch(
card -> RnrStatus.INIT.getCode() == card.getRnrStatus() || RnrStatus.RNR.getCode() == card.getRnrStatus())) {
throw new CuscUserException("", "输入的卡信息已存在实名记录");
}
if (detailType.getType().equals(VinCardCheckBussinessDetailType.NATURALPERSON_NEW.getType())
|| detailType.getType().equals(VinCardCheckBussinessDetailType.ENTERPRISE.getType())
|| detailType.getType().equals(VinCardCheckBussinessDetailType.VEHICLE.getType())) {
//自然人 - 新车 || 企业实名 || 车企实名
if (mgRnrCardInfoList.stream().anyMatch(
card -> RnrStatus.INIT.getCode() == card.getRnrStatus() || RnrStatus.RNR.getCode() == card.getRnrStatus())) {
// throw new CuscUserException("", "vin已经存在实名信息,请走一车多卡流程");
throw new CuscUserException("", "您提交的VIN号已实名,请勿重复提交实名!");
}
} else if(detailType.getType().equals(VinCardCheckBussinessDetailType.ONECAR_MORECARD.getType())){
//一车多卡
List<MgRnrCardInfoDTO> rnrCardList = mgRnrCardInfoList.stream()
.filter(card -> card.getRnrStatus() == RnrStatus.RNR.getCode()).collect(Collectors.toList());
if (CollectionUtils.isEmpty(rnrCardList)) {
throw new CuscUserException("", "该vin号未查询到实名的卡信息");
}
String rnrId = rnrCardList.get(0).getRnrId();
MgRnrInfoDTO rnrInfoQuery = new MgRnrInfoDTO();
rnrInfoQuery.setUuid(rnrId);
Response<MgRnrInfoDTO> rnrInfoDTOResponse = rnrInfoClient.getByUuid(rnrInfoQuery);
if (null != rnrInfoDTOResponse && rnrInfoDTOResponse.isSuccess() && null != rnrInfoDTOResponse.getData()) {
MgRnrInfoDTO data = rnrInfoDTOResponse.getData();
return new VinCardCheckResultDTO().setPhone(data.getPhone()).setName(data.getFullName());
}
}
return null;
}
private List<MgRnrCardInfoDTO> queryCardListByIccidList(List<String> iccidList){
MgRnrCardInfoDTO query = new MgRnrCardInfoDTO();
query.setIccidList(iccidList);
Response<List<MgRnrCardInfoDTO>> response = cardInfoClient.queryByList(query);
if (null == response || !response.isSuccess()) {
throw new CuscUserException("","查询卡信息失败");
}
return response.getData();
}
/*private List<MgRnrCardInfoDTO> queryCardListByIccidListAndVin(List<String> iccidList,String vin){
MgRnrCardInfoDTO query = new MgRnrCardInfoDTO();
query.setIccidList(iccidList);
//query.setIotId(vin);
Response<List<MgRnrCardInfoDTO>> response = cardInfoClient.queryByList(query);
if (null == response || !response.isSuccess()) {
throw new CuscUserException("","查询卡信息失败");
}
return response.getData();
}*/
private List<MgRnrCardInfoDTO> queryCardListByVin(String vin){
MgRnrCardInfoDTO query = new MgRnrCardInfoDTO();
query.setIotId(vin);
Response<List<MgRnrCardInfoDTO>> response = cardInfoClient.queryByList(query);
if (null == response || !response.isSuccess()) {
throw new CuscUserException("","查询卡信息失败");
}
return response.getData();
}
private void checkCardExsit(List<String> cardList){
boolean allMatch = cardList.parallelStream().allMatch(iccid -> {
Response<IccidDetailDTO> response = simVehicleRelService.getDetailByIccid(iccid);
log.info("查询卡是否存在,iccid = {},response = {}",iccid,JSONObject.toJSONString(response));
return response != null && response.isSuccess() && null != response.getData();
});
if (!allMatch) {
throw new CuscUserException("","提交的卡信息未查询到");
}
}
private void checkVinCardRelation(List<String> iccidList, String vin) {
boolean allMatch = iccidList.stream().allMatch(iccid -> {
Response<VinIccidDTO> response = simVehicleRelService.getVinByIccid(iccid);
log.info("查询车卡匹配,iccid = {},输入vin = {},response = {}", iccid, vin, JSONObject.toJSONString(response));
if (null == response || !response.isSuccess()) {
throw new CuscUserException("", "查询车卡匹配关系失败");
}
VinIccidDTO data = response.getData();
if (null == data || StringUtils.isBlank(data.getVin())) {
return true;
}
return vin.equals(data.getVin());
});
if (!allMatch) {
throw new CuscUserException("", "卡信息的vin码和输入的vin不一致");
}
}
@Override
public VinCardCheckMessageResultDTO checkVinCardMessage(VinCardCheckMessageRequestDTO requestDTO) {
VinCardCheckBussinessDetailType detailType = VinCardCheckBussinessDetailType.getBytype(requestDTO.getBusinessType());
//绑定卡的 校验
String bindVinCardCheckHandlerName = detailType.getBindVinCardCheckHandlerName();
VinCardCheckMessageResultDTO bindResultDto = null;
if (StringUtils.isNotBlank(bindVinCardCheckHandlerName)){
VinCardCheckMessageHandler bindHandler = SpringUtil.getBean(bindVinCardCheckHandlerName, VinCardCheckMessageHandler.class);
bindResultDto = bindHandler.checkVinCard(requestDTO.getVin(), requestDTO.getBindIccidList(), detailType);
}
//解绑的卡的 校验
String unBindVinCardCheckHandlerName = detailType.getUnBindVinCardCheckHandlerName();
VinCardCheckMessageResultDTO unBindResultDto = null;
if (StringUtils.isNotBlank(unBindVinCardCheckHandlerName)) {
VinCardCheckMessageHandler unBindHandler = SpringUtil.getBean(unBindVinCardCheckHandlerName, VinCardCheckMessageHandler.class);
unBindResultDto = unBindHandler.checkVinCard(requestDTO.getVin(), requestDTO.getUnBindIccidList(), detailType);
}
if (bindResultDto != null && unBindResultDto != null) {
bindResultDto.merge(unBindResultDto);
return bindResultDto;
}
if (null != bindResultDto) {
return bindResultDto;
} else if (null != unBindResultDto){
return unBindResultDto;
} else {
throw new CuscUserException(ResponseCode.SYSTEM_ERROR.getCode(),"校验结果为空");
}
}
@Override
public VinCheckResultDTO checkVin(VinCheckRequestDTO requestDTO) {
VinCheckResultDTO resultDTO = new VinCheckResultDTO();
List<VinCheckResultDTO.VinCheckDetailDTO> checkList = requestDTO.getVinList().parallelStream().map(vin -> {
VinCheckResultDTO.VinCheckDetailDTO detailDTO = new VinCheckResultDTO.VinCheckDetailDTO();
detailDTO.setVin(vin);
List<VinIccidDTO> iccidDTOList = null;
try {
Response<List<VinIccidDTO>> response = simVehicleRelService.getIccidByVin(vin);
log.info("checkVin getIccidByVin vin = {},response = {}", vin, JSONObject.toJSONString(response));
iccidDTOList = response.getData();
} catch (Exception e) {
log.error("checkVin getIccidByVin has error vin = {}", vin, e);
}
if (CollectionUtils.isEmpty(iccidDTOList)) {
detailDTO.setErrorMsg("缺乏车卡关系");
} else {
List<MgRnrCardInfoDTO> mgRnrCardInfoList = queryCardListByVin(vin);
mgRnrCardInfoList = filterManufacturerRnr(mgRnrCardInfoList);
if (mgRnrCardInfoList.stream().anyMatch(
card -> RnrStatus.INIT.getCode() == card.getRnrStatus() || RnrStatus.RNR.getCode() == card.getRnrStatus())) {
detailDTO.setErrorMsg("已绑定");
}
}
detailDTO.setCheckResult(StringUtils.isBlank(detailDTO.getErrorMsg()));
if (!CollectionUtils.isEmpty(iccidDTOList)){
detailDTO.setIccidList(iccidDTOList.stream().map(VinIccidDTO::getIccid).distinct().collect(Collectors.toList()));
}
return detailDTO;
}).collect(Collectors.toList());
resultDTO.setCheckList(checkList);
return resultDTO;
}
@Override
public List<MgRnrCardInfoDTO> filterManufacturerRnr(List<MgRnrCardInfoDTO> cardInfoList) {
if (CollectionUtils.isEmpty(cardInfoList)) {
return Collections.emptyList();
}
List<String> orderIdList = cardInfoList.stream().filter(card->RnrStatus.RNR.getCode() == card.getRnrStatus())
.map(MgRnrCardInfoDTO::getOrderId).distinct().collect(Collectors.toList());
if (CollectionUtils.isEmpty(orderIdList)) {
//没有实名的卡 返回cardInfoList
return cardInfoList;
}
RnrOrderDTO orderQuery = new RnrOrderDTO();
orderQuery.setUuidList(orderIdList);
orderQuery.setOrderType(RnrOrderType.CARMAKER_NEW_VEHICLE.getCode());
List<RnrOrderDTO> orderList = orderClient.queryByList(orderQuery).getData();
List<String> manufacturerRnrOrderIdList = orderList.stream().map(RnrOrderDTO::getUuid).collect(Collectors.toList());
return cardInfoList.stream().filter(card->!manufacturerRnrOrderIdList.contains(card.getOrderId())).collect(Collectors.toList());
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.cusc.nirvana.user.rnr.fp.constants.MbCodeEnum;
import com.cusc.nirvana.user.rnr.fp.service.OperatorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* @className: OperatorServiceImpl
* @description: 运营商配置
* @author: jk
* @date: 2022/8/2 11:19
* @version: 1.0
**/
@Service
@Slf4j
public class OperatorServiceImpl implements OperatorService {
@Value("${mbCodeEnum.cmcc}")
private String cmcc;
@Value("${mbCodeEnum.cucc}")
private String cucc;
@Value("${mbCodeEnum.ctcc}")
private static String ctcc;
@Value("${mbCodeEnum.qt}")
private static String qt;
@Override
public String get(String iccid) {
if (cmcc.indexOf(iccid.substring(0, 6)) != -1) {
return MbCodeEnum.CMCC.getCode();
}
if (cucc.indexOf(iccid.substring(0, 6)) != -1) {
return MbCodeEnum.CUCC.getCode();
}
if (ctcc.indexOf(iccid.substring(0, 6)) != -1) {
return MbCodeEnum.CTCC.getCode();
}
if (qt.indexOf(iccid.substring(0, 6)) != -1) {
return MbCodeEnum.QT.getCode();
}
return null;
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.eiam.client.OrganizationClient;
import com.cusc.nirvana.user.eiam.dto.OrganizationDTO;
import com.cusc.nirvana.user.rnr.fp.constants.OrganBizzTypeEnum;
import com.cusc.nirvana.user.rnr.fp.service.IOrganService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
/**
* Description:组织操作service实现类
* <br />
* CreateDate 2022-07-06 19:33:31
*
* @author yuyi
**/
@Service
@Slf4j
public class OrganServiceImpl implements IOrganService {
@Resource
private OrganizationClient organizationClient;
@Override
public Response<OrganizationDTO> getCarSubOrganByOrgId(OrganizationDTO bean) {
//根据组织id查询组织信息
OrganizationDTO organ = new OrganizationDTO();
organ.setUuid(bean.getUuid());
organ.setTenantNo(bean.getTenantNo());
Response<OrganizationDTO> organResp = organizationClient.getByUuid(organ);
if (!organResp.isSuccess()) {
return Response.createError(organResp.getMsg(), organResp.getCode());
}
organ = organResp.getData();
return getCarSubOrganByQueryCodePrivate(organ);
}
@Override
public Response<OrganizationDTO> getCarSubOrganByQueryCodePrivate(OrganizationDTO bean) {
//根据当前组织的查询编码查询组织信息
List<String> uuidList = Arrays.asList(bean.getQueryCode().split("-"));
OrganizationDTO organSub = new OrganizationDTO();
organSub.setTenantNo(bean.getTenantNo());
organSub.setUuidList(uuidList);
Response<List<OrganizationDTO>> orgListResp = organizationClient.queryByList(organSub);
if (!orgListResp.isSuccess()) {
return Response.createError(orgListResp.getMsg(), orgListResp.getCode());
}
if (CollectionUtils.isEmpty(orgListResp.getData())) {
return Response.createSuccess();
}
for (OrganizationDTO tmp : orgListResp.getData()) {
if (OrganBizzTypeEnum.CAR_FACTORY.getCode() == tmp.getBizType().intValue()
|| OrganBizzTypeEnum.CAR_SUB_ORGAN.getCode() == tmp.getBizType().intValue()) {
return Response.createSuccess(tmp);
}
}
return Response.createSuccess();
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.eiam.client.OrganizationClient;
import com.cusc.nirvana.user.eiam.dto.OrganizationDTO;
import com.cusc.nirvana.user.rnr.fp.constants.OrganBizzTypeEnum;
import com.cusc.nirvana.user.rnr.fp.service.OrganizationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
/**
* @className: OrganizationServiceImpl
* @description:
* @author: jk
* @date: 2022/6/10 10:37
* @version: 1.0
**/
@Service
@Slf4j
public class OrganizationServiceImpl implements OrganizationService {
@Resource
private OrganizationClient organizationClient;
@Override
public Response<OrganizationDTO> getCarSubOrganByQueryCode(OrganizationDTO bean) {
//根据组织id查询组织信息
OrganizationDTO organ = new OrganizationDTO();
organ.setUuid(bean.getUuid());
organ.setTenantNo(bean.getTenantNo());
Response<OrganizationDTO> organResp = organizationClient.getByUuid(organ);
if (!organResp.isSuccess()) {
return Response.createError(organResp.getMsg(), organResp.getCode());
}
organ = organResp.getData();
return getCarSubOrganByQueryCodePrivate(organ);
}
@Override
public Response<OrganizationDTO> getCarSubOrganByQueryCodePrivate(OrganizationDTO bean) {
//根据当前组织的查询编码查询组织信息
List<String> uuidList = Arrays.asList(bean.getQueryCode().split("-"));
OrganizationDTO organSub = new OrganizationDTO();
organSub.setTenantNo(bean.getTenantNo());
organSub.setUuidList(uuidList);
Response<List<OrganizationDTO>> orgListResp = organizationClient.queryByList(organSub);
if (!orgListResp.isSuccess()) {
return Response.createError(orgListResp.getMsg(), orgListResp.getCode());
}
if (CollectionUtils.isEmpty(orgListResp.getData())) {
return Response.createSuccess();
}
for (OrganizationDTO tmp : orgListResp.getData()) {
if (OrganBizzTypeEnum.CAR_FACTORY.getCode() == tmp.getBizType().intValue()
|| OrganBizzTypeEnum.CAR_SUB_ORGAN.getCode() == tmp.getBizType().intValue()) {
return Response.createSuccess(tmp);
}
}
return Response.createSuccess();
}
}
package com.cusc.nirvana.user.rnr.fp.service.impl;
import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;
import com.alibaba.excel.util.IoUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.rnr.fp.common.ResponseCode;
import com.cusc.nirvana.user.rnr.fp.config.ChineseFontComponent;
import com.cusc.nirvana.user.rnr.fp.dto.FileDownloadDTO;
import com.cusc.nirvana.user.rnr.fp.dto.FileRecordDTO;
import com.cusc.nirvana.user.rnr.fp.service.IFileService;
import com.cusc.nirvana.user.rnr.fp.util.RnrFpRestTemplateUtils;
import com.cusc.nirvana.user.util.CuscStringUtils;
import com.cusc.nirvana.user.util.DateUtils;
import com.cusc.nirvana.user.util.crypt.DataCryptService;
import com.cusc.nirvana.user.util.crypt.Sm4Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.im4java.core.CompositeCmd;
import org.im4java.core.IMOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author stayAnd
* @date 2022/6/22
*/
@Service
@Slf4j
public class OssFileServiceImpl implements IFileService {
/**
* GraphicsMagick 安装目录
*/
public static final String PATH_GRAPHICS_MAGICK = "/data/GraphicsMagick/bin";
@Value("${oss.endpoint}")
private String endpoint;
@Value("${oss.accessKeyId}")
private String accessKeyId;
@Value("${oss.accessKeySecret}")
private String accessKeySecret;
@Value("${oss.bucketName}")
private String bucketName;
@Value("${rnr.image.watermark.position:8}")
public int watermarkPosition;
@Value("${rnr.image.watermark.fontcolor:#DC143C}")
public String watermarkFontColor;
@Value("${rnr.image.watermark.alpha:50}")
public int watermarkAlpha;
@Value("${rnr.image.watermark.fontsize:15}")
public int watermarkFontSize;
@Value("${rnr.image.watermark.fonttype:HeiTi}")
public String watermarkFontType;
@Value("${rnr.image.watermark.content:仅限用于实名业务}")
private String watermarkContent;
@Value("${rnr.image.watermark.source:/data/imageTemp/source/}")
private String sourceBasePath;
@Value("${rnr.image.watermark.water:/data/imageTemp/water/}")
private String waterBasePath;
@Value("${rnr.image.watermark.target:/data/imageTemp/target/}")
private String targetBasePath;
@Resource
private ChineseFontComponent chineseFontComponent;
@Resource
private ExecutorService textWaterMarkThreadPool4createWaterMark;
@Autowired
private DataCryptService dataCryptService;
@Value("${T1.picturePower}")
private boolean picturePower;
@Override
public String upLoadImage(InputStream inputStream,String suffix) {
return upLoadFile(inputStream,suffix);
}
@Override
public String upLoadFile(InputStream inputStream,String suffix) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
String ossFileKey = CuscStringUtils.generateUuid()+"."+suffix;
PutObjectRequest request = new PutObjectRequest(bucketName,ossFileKey,inputStream);
ossClient.putObject(request);
ossClient.shutdown();
return ossFileKey;
}
//方案:IM4JAVA+GraphicsMagick实现中文水印
@Override
public String doMarkText(MultipartFile reqFile, String userId) throws Exception {
String fontType = watermarkFontType;//字体
String colorStr = watermarkFontColor; //颜色
int alpha = watermarkAlpha;
int fontSize = watermarkFontSize;
String filePre = "[" + UUID.randomUUID().toString().replace("-", "") + "]";
String fileName = filePre + reqFile.getOriginalFilename();
// 1) file-->本地存储到sourcePath
File localImageFile = new File(new File(sourceBasePath).getAbsolutePath() + "/" + fileName);
if (!localImageFile.getParentFile().exists()) {
localImageFile.getParentFile().mkdirs();
}
reqFile.transferTo(localImageFile);
// 将文字生成图片,再合成
// 1、生成透明的背景图片
File watermarkImage = new File(new File(waterBasePath).getAbsolutePath() + "/" + fileName);
String watermarkContent = getWatermarkContent(userId);
boolean res = textWaterMarkThreadPool4createWaterMark.submit(() -> this.convertFontToImage(watermarkContent, fontType, fontSize, colorStr, watermarkImage.getAbsolutePath())).get();
if (!res) {
throw new CuscUserException("500", "文字水印生成临时文件异常");
}
// 2、合成图片
String waterPath = watermarkImage.getAbsolutePath();
String sourceImagePath = sourceBasePath + fileName;
String targetImagePath = targetBasePath + fileName;
int[] watermarkImgSide = getImageSide(watermarkImage.getAbsolutePath());
int[] srcImgSide = getImageSide(sourceImagePath);
int[] xy = getXY(srcImgSide, watermarkImgSide, watermarkPosition, 0, 0);
CompositeCmd cmd = new CompositeCmd(true);
cmd.setSearchPath(PATH_GRAPHICS_MAGICK);
IMOperation op = new IMOperation();
op.dissolve(alpha);
op.geometry(watermarkImgSide[0], watermarkImgSide[1], xy[0], xy[1]);
op.addImage(waterPath);
op.addImage(sourceImagePath);
op.addImage(targetImagePath);
cmd.run(op);
return fileName;
}
@Override
public String upLoadImgBase64(String base64, String suffix) {
try {
byte[] bytes = Base64Decoder.decode(base64);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
return upLoadImage(inputStream,suffix);
} catch (Exception e) {
log.error("upLoadImgBase64 has error");
}
return "";
}
@Override
public String upLoadFileBase64(String base64, String suffix) {
try {
byte[] bytes = Base64Decoder.decode(base64);
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
return upLoadFile(inputStream,suffix);
} catch (Exception e) {
log.error("upLoadImgBase64 has error");
}
return "";
}
@Override
public String getFileUrl(String fileKey) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
Date date = new Date(System.currentTimeMillis() +(3600L * 1000) );
URL url = ossClient.generatePresignedUrl(bucketName,fileKey,date);
log.info("OssFileServiceImpl getFileUrl fileKey = {},url = {}",fileKey,url.toString());
ossClient.shutdown();
return url.toString();
}
@Override
public String downLoadBase64(String fileKey) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
GetObjectRequest request = new GetObjectRequest(bucketName,fileKey);
OSSObject object = ossClient.getObject(request);
InputStream inputStream = object.getObjectContent();
byte[] bytes = IoUtils.toByteArray(inputStream);
byte[] imageContent = new byte[1024];
//解密失败,原文返回
try {
imageContent = Sm4Util.decryptEcbPaddingByte(dataCryptService.getSm4Key().getBytes(), bytes);
} catch (Exception e) {
return Base64Encoder.encode(bytes);
}
//解密成功 解密返回
return Base64Encoder.encode(picturePower?imageContent:bytes);
} catch (Exception e) {
e.printStackTrace();
throw new CuscUserException(ResponseCode.SYSTEM_ERROR.getCode(),"文件oss下载失败");
} finally {
ossClient.shutdown();
}
}
@Override
public Double getFileSize(String fileKey) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
boolean existFlag = ossClient.doesObjectExist(bucketName, fileKey);
if(!existFlag){
throw new CuscUserException("500","文件不存在");
}
ObjectMetadata objectMetadata = ossClient.getObjectMetadata(bucketName, fileKey);
Double fileSize = (double) objectMetadata.getContentLength()/1024;
ossClient.shutdown();
return fileSize;
}
@Override
public byte[] downLoadBytes(String fileKey) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
GetObjectRequest request = new GetObjectRequest(bucketName,fileKey);
OSSObject object = ossClient.getObject(request);
InputStream inputStream = object.getObjectContent();
try {
byte[] bytes = IoUtils.toByteArray(inputStream);
ossClient.shutdown();
return bytes;
} catch (Exception e){
throw new CuscUserException(ResponseCode.SYSTEM_ERROR.getCode(),"文件oss bytes下载失败");
}
}
/**---------------------------------------私有化方法-----------------------------------------------------------------------*/
private String getWatermarkContent(String userId) {
StringBuilder rv = new StringBuilder(watermarkContent);
rv.append("[");
rv.append(StringUtils.isBlank(userId) ? "" : userId);
rv.append("]");
rv.append("[");
rv.append(DateUtils.currentTimeStr());
rv.append("]");
return rv.toString();
}
private int[] getXY(int[] image, int[] watermark, int position, int x, int y) {
int[] xy = new int[2];
if (position == 1) {
xy[0] = x;
xy[1] = y;
} else if (position == 2) {
xy[0] = (image[0] - watermark[0]) / 2; //横向边距
xy[1] = y; //纵向边距
} else if (position == 3) {
xy[0] = image[0] - watermark[0] - x;
xy[1] = y;
} else if (position == 4) {
xy[0] = x;
xy[1] = (image[1] - watermark[1]) / 2;
} else if (position == 5) {
xy[0] = (image[0] - watermark[0]) / 2;
xy[1] = (image[1] - watermark[1]) / 2;
} else if (position == 6) {
xy[0] = image[0] - watermark[0] - x;
xy[1] = (image[1] - watermark[1]) / 2;
} else if (position == 7) {
xy[0] = x;
xy[1] = image[1] - watermark[1] - y;
} else if (position == 8) {
xy[0] = (image[0] - watermark[0]) / 2;
xy[1] = image[1] - watermark[1] - y;
} else {
xy[0] = image[0] - watermark[0] - x;
xy[1] = image[1] - watermark[1] - y;
}
return xy;
}
private int[] getImageSide(String imgPath) throws IOException {
int[] side = new int[2];
Image img = ImageIO.read(new File(imgPath));
side[0] = img.getWidth(null);
side[1] = img.getHeight(null);
return side;
}
/**
* 将文字转换为图片(解决中文字符乱码以及文字透明度问题)
*
* @param text 文本内容
* @param fontType 字体类型(HeiTi、KaiTi、SongTi)
* @param fontSize 字体大小
* @param fontColor 字体颜色
* @param outFile 输出文件路径
*/
private boolean convertFontToImage(String text, String fontType, Integer fontSize, String fontColor, String outFile) {
long startTime = System.currentTimeMillis();
Color textColor = Color.BLACK;
if (StringUtils.isNotBlank(fontColor)) {
textColor = new Color(Integer.valueOf(fontColor, 16));
}
// 获取字体库映射字体集
Font font = chineseFontComponent.getChineseFont(fontType).deriveFont(Font.PLAIN, fontSize);
File file = new File(outFile);
// 获取font的样式应用在str上的整个矩形
Rectangle2D r = font.getStringBounds(text, new FontRenderContext(AffineTransform.getScaleInstance(1, 1), false, false));
// 获取单个字符的高度
int unitHeight = (int) Math.floor(r.getHeight());
// 获取整个str用了font样式的宽度这里用四舍五入后+1保证宽度绝对能容纳这个字符串作为图片的宽度
int width = (int) Math.round(r.getWidth()) + 1;
// 把单个字符的高度+3保证高度绝对能容纳字符串作为图片的高度
int height = unitHeight + 3;
// 创建图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = image.createGraphics();
g2d.setStroke(new BasicStroke(1));
g2d.setColor(textColor); // 在换成所需要的字体颜色
g2d.setFont(font);
g2d.drawString(text, 0, font.getSize());
try {
ImageIO.write(image, "png", file); // 输出png图片
} catch (IOException e) {
log.error("文字水印生成临时文件出现异常", e);
return false;
}
log.info("生成临时文件时间:{} ms", (System.currentTimeMillis() - startTime));
return true;
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment