This commit is contained in:
2023-03-04 16:29:55 +08:00
commit 397ba75479
1007 changed files with 109050 additions and 0 deletions

View File

@@ -0,0 +1,234 @@
package com.jsowell.service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jsowell.common.constant.CacheConstants;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.page.PageResponse;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.enums.uniapp.BalanceChangesEnum;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.util.JWTUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.id.IdUtils;
import com.jsowell.pile.domain.MemberBasicInfo;
import com.jsowell.pile.domain.MemberWalletInfo;
import com.jsowell.pile.dto.MemberRegisterAndLoginDTO;
import com.jsowell.pile.dto.MemberRegisterDTO;
import com.jsowell.pile.dto.UniAppQueryMemberBalanceDTO;
import com.jsowell.pile.dto.WechatLoginDTO;
import com.jsowell.pile.service.IMemberBasicInfoService;
import com.jsowell.pile.service.IPileMerchantInfoService;
import com.jsowell.pile.transaction.dto.MemberTransactionDTO;
import com.jsowell.pile.transaction.service.TransactionService;
import com.jsowell.pile.vo.uniapp.MemberVO;
import com.jsowell.pile.vo.uniapp.MemberWalletLogVO;
import com.jsowell.wxpay.service.WxAppletRemoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
@Service
public class MemberService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private RedisCache redisCache;
@Autowired
private TransactionService transactionService;
@Autowired
private IMemberBasicInfoService memberBasicInfoService;
@Autowired
private IPileMerchantInfoService pileMerchantInfoService;
@Autowired
private WxAppletRemoteService wxAppletRemoteService;
/**
* 校验短信验证码
* @param dto
*/
public void checkVerificationCode(MemberRegisterAndLoginDTO dto) {
// 取出缓存中的验证码进行对比,如果缓存中没有,则超时
String captchaCode = redisCache.getCacheObject(CacheConstants.SMS_VERIFICATION_CODE_KEY + dto.getMobileNumber());
if (StringUtils.isEmpty(captchaCode)) {
throw new BusinessException(ReturnCodeEnum.CODE_VERIFICATION_CODE_TIMEOUT_ERROR);
}
// 如果缓存中有,但与实际不一致,则为验证码错误
if (!StringUtils.equals(captchaCode, dto.getVerificationCode())) {
throw new BusinessException(ReturnCodeEnum.CODE_VERIFICATION_CODE_ERROR);
}
}
/**
* 短信验证码登录注册
* @param dto
* @return
*/
public String memberRegisterAndLogin(MemberRegisterAndLoginDTO dto) {
// 校验短信验证码 两种情况不能通过校验1-验证码错误2-超时 验证码10分钟有效
checkVerificationCode(dto);
String merchantId = "";
return memberRegisterAndLogin(dto.getMobileNumber(), merchantId, null);
}
/**
* 公共登陆注册方法
* @param phoneNumber 手机号
* @param merchantId 商户id
* @return
*/
private String memberRegisterAndLogin(String phoneNumber, String merchantId, String openId) {
if (StringUtils.isBlank(phoneNumber)) {
throw new BusinessException(ReturnCodeEnum.CODE_GET_MOBILE_NUMBER_BY_CODE_ERROR);
}
// if (Objects.isNull(merchantId)) {
// throw new BusinessException(ReturnCodeEnum.CODE_GET_MERCHANT_ID_BY_APP_ID_ERROR);
// }
// 查询手机号码是否注册过
MemberBasicInfo memberBasicInfo = memberBasicInfoService.selectInfoByMobileNumberAndMerchantId(phoneNumber, merchantId);
if (Objects.isNull(memberBasicInfo)) {
// 不存在则新增数据
String memberId = IdUtils.getMemberId();
memberBasicInfo = new MemberBasicInfo();
memberBasicInfo.setStatus(Constants.ONE);
memberBasicInfo.setMemberId(memberId);
memberBasicInfo.setNickName("会员" + memberId);
memberBasicInfo.setMobileNumber(phoneNumber);
memberBasicInfo.setMerchantId(Long.valueOf(merchantId));
memberBasicInfo.setOpenId(openId);
// 首次新建会员,同时新建会员钱包
MemberWalletInfo memberWalletInfo = MemberWalletInfo.builder().memberId(memberId).build();
MemberTransactionDTO memberTransactionDTO = MemberTransactionDTO.builder()
.memberBasicInfo(memberBasicInfo)
.memberWalletInfo(memberWalletInfo)
.build();
transactionService.createMember(memberTransactionDTO);
} else {
if (StringUtils.isBlank(memberBasicInfo.getOpenId()) && StringUtils.isNotBlank(openId)) {
memberBasicInfo.setOpenId(openId);
memberBasicInfoService.updateMemberBasicInfo(memberBasicInfo);
}
}
// 服务器生成token返给前端
String memberToken = JWTUtils.createMemberToken(memberBasicInfo.getMemberId(), memberBasicInfo.getNickName());
// log.info("memToken:{}", memberToken);
return memberToken;
}
/**
* 微信一键登录
* @param dto
*/
public String wechatLogin(WechatLoginDTO dto) {
// 通过微信传的code获取手机号码
String mobileNumber = wxAppletRemoteService.getMobileNumberByCode(dto.getCode());
if (StringUtils.isBlank(mobileNumber)) {
throw new BusinessException(ReturnCodeEnum.CODE_GET_MOBILE_NUMBER_BY_CODE_ERROR);
}
// 通过appid获取运营商id
String merchantId = pileMerchantInfoService.getMerchantIdByAppId(dto.getAppId());
// if (Objects.isNull(merchantId)) {
// throw new BusinessException(ReturnCodeEnum.CODE_GET_MERCHANT_ID_BY_APP_ID_ERROR);
// }
// 通过code获取openId
String openId = "";
try {
openId = getOpenIdByCode(dto.getOpenIdCode());
} catch (Exception e) {
log.error("getOpenIdByCode发生异常", e);
}
// 查询手机号码是否注册过
return memberRegisterAndLogin(mobileNumber, merchantId, openId);
}
/**
* 获取openId
* @param code
* @return
*/
public String getOpenIdByCode(String code) {
return wxAppletRemoteService.getOpenIdByCode(code);
}
/**
* 处理用户信息
*
* @param dto 用户个人信息
*/
public void handleUserInfo(MemberRegisterDTO dto) {
// 通过用户手机号查询数据库,如果数据库中存在,则更新
MemberBasicInfo memberBasicInfo = memberBasicInfoService.selectInfoByMobileNumber(dto.getMobileNumber());
if (Objects.nonNull(memberBasicInfo)) {
MemberBasicInfo memberInfo = MemberBasicInfo.builder()
.avatarUrl(dto.getAvatarUrl())
.mobileNumber(dto.getMobileNumber())
.nickName(dto.getNickName())
.build();
memberBasicInfoService.updateMemberBasicInfo(memberInfo);
}
}
/**
* 通过memberToken获取用户账户信息
*
* @param memberId
* @return
*/
public MemberVO getMemberInfoByMemberId(String memberId) {
MemberVO memberVO = memberBasicInfoService.queryMemberInfoByMemberId(memberId);
if (Objects.nonNull(memberVO)) {
memberVO.setTotalAccountAmount(memberVO.getPrincipalBalance().add(memberVO.getGiftBalance()));
}
return memberVO;
}
/**
* 查询用户账户余额变动信息
*
* @param dto
*/
public PageResponse getMemberBalanceChanges(UniAppQueryMemberBalanceDTO dto) {
// 获取分页信息以及memberId
int pageNum = dto.getPageNum() == 0 ? 1 : dto.getPageNum();
int pageSize = dto.getPageSize() == 0 ? 10 : dto.getPageSize();
String memberId = dto.getMemberId();
String type = dto.getType();
if (!StringUtils.equals("1", type) && !StringUtils.equals("2", type)) {
type = "";
}
// 分页
PageHelper.startPage(pageNum, pageSize);
List<MemberWalletLogVO> list = memberBasicInfoService.getMemberBalanceChanges(memberId, type);
PageInfo<MemberWalletLogVO> pageInfo = new PageInfo<>(list);
for (MemberWalletLogVO walletLogVO : pageInfo.getList()) {
String subType = walletLogVO.getSubType();
String subTypeValue = BalanceChangesEnum.getValueByCode(subType);
if (StringUtils.isNotBlank(subTypeValue)) {
walletLogVO.setSubType(subTypeValue);
}
// walletLogVO.setTotalAccountAmount(walletLogVO.getPrincipalBalance().add(walletLogVO.getGiftBalance()));
}
PageResponse pageResponse = PageResponse.builder()
.pageSize(pageSize)
.pageNum(pageNum)
.list(pageInfo.getList())
.pages(pageInfo.getPages())
.total(pageInfo.getTotal())
.build();
return pageResponse;
}
}

View File

@@ -0,0 +1,780 @@
package com.jsowell.service;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.ykc.RealTimeMonitorData;
import com.jsowell.common.core.page.PageResponse;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.enums.MemberWalletEnum;
import com.jsowell.common.enums.ykc.ActionTypeEnum;
import com.jsowell.common.enums.ykc.OrderPayModeEnum;
import com.jsowell.common.enums.ykc.OrderPayRecordEnum;
import com.jsowell.common.enums.ykc.OrderPayStatusEnum;
import com.jsowell.common.enums.ykc.OrderStatusEnum;
import com.jsowell.common.enums.ykc.PayModeEnum;
import com.jsowell.common.enums.ykc.ScenarioEnum;
import com.jsowell.common.enums.ykc.PileConnectorDataBaseStatusEnum;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.util.DateUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.id.IdUtils;
import com.jsowell.netty.command.ykc.StartChargingCommand;
import com.jsowell.netty.service.yunkuaichong.YKCPushCommandService;
import com.jsowell.pile.domain.MemberTransactionRecord;
import com.jsowell.pile.domain.OrderBasicInfo;
import com.jsowell.pile.domain.OrderDetail;
import com.jsowell.pile.domain.OrderPayRecord;
import com.jsowell.pile.domain.WxpayCallbackRecord;
import com.jsowell.pile.dto.BasicPileDTO;
import com.jsowell.pile.dto.GenerateOrderDTO;
import com.jsowell.pile.dto.PayOrderDTO;
import com.jsowell.pile.dto.PayOrderSuccessCallbackDTO;
import com.jsowell.pile.dto.PaymentScenarioDTO;
import com.jsowell.pile.dto.QueryConnectorListDTO;
import com.jsowell.pile.dto.QueryOrderDTO;
import com.jsowell.pile.dto.SettleOrderDTO;
import com.jsowell.pile.dto.StopChargingDTO;
import com.jsowell.pile.dto.UniAppQueryOrderDTO;
import com.jsowell.pile.dto.WeixinPayDTO;
import com.jsowell.pile.service.IMemberBasicInfoService;
import com.jsowell.pile.service.IMemberTransactionRecordService;
import com.jsowell.pile.service.IOrderBasicInfoService;
import com.jsowell.pile.service.IOrderPayRecordService;
import com.jsowell.pile.service.IPileBillingTemplateService;
import com.jsowell.pile.service.IPileConnectorInfoService;
import com.jsowell.pile.service.WechatPayService;
import com.jsowell.pile.service.WxpayCallbackRecordService;
import com.jsowell.pile.transaction.dto.OrderTransactionDTO;
import com.jsowell.pile.transaction.service.TransactionService;
import com.jsowell.pile.vo.base.PileInfoVO;
import com.jsowell.pile.vo.uniapp.MemberVO;
import com.jsowell.pile.vo.uniapp.OrderVO;
import com.jsowell.pile.vo.uniapp.PileConnectorDetailVO;
import com.jsowell.pile.vo.uniapp.UniAppOrderVO;
import com.jsowell.pile.vo.web.BillingTemplateVO;
import com.jsowell.pile.vo.web.OrderDetailInfoVO;
import com.jsowell.pile.vo.web.UpdateMemberBalanceDTO;
import com.jsowell.wxpay.dto.WeChatRefundDTO;
import com.jsowell.wxpay.response.WechatPayNotifyParameter;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class OrderService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Autowired
private TransactionService pileTransactionService;
@Autowired
private IPileBillingTemplateService pileBillingTemplateService;
@Autowired
private IOrderBasicInfoService orderBasicInfoService;
@Autowired
private PileRemoteService pileRemoteService;
@Autowired
private YKCPushCommandService ykcPushCommandService;
@Autowired
private PileService pileService;
@Autowired
private MemberService memberService;
@Autowired
private IMemberBasicInfoService memberBasicInfoService;
@Autowired
private IOrderPayRecordService orderPayRecordService;
@Autowired
private WechatPayService wechatPayService;
@Autowired
private WxpayCallbackRecordService wxpayCallbackRecordService;
@Autowired
private IPileConnectorInfoService pileConnectorInfoService;
@Autowired
private IMemberTransactionRecordService memberTransactionRecordService;
@Autowired
private RedisCache redisCache;
/**
* 生成订单
*
* @param dto
* @return
*/
public String generateOrder(GenerateOrderDTO dto) {
log.info("generateOrder param:{}", JSONObject.toJSONString(dto));
// 处理前端传的参数
analysisPileParameter(dto);
// 校验充电桩相关的信息
checkPileInfo(dto);
// 保存订单到数据库 saveOrder2Database
String orderCode = saveOrder2Database(dto);
return orderCode;
}
/**
* 订单支付
*
* @param dto
*/
public Map<String, Object> payOrder(PayOrderDTO dto) throws Exception {
Map<String, Object> resultMap = Maps.newHashMap();
OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByOrderCode(dto.getOrderCode());
if (orderInfo == null) {
throw new BusinessException(ReturnCodeEnum.CODE_QUERY_ORDER_NULL_ERROR);
}
if (!StringUtils.equals(orderInfo.getPayStatus(), "0")) {
// 订单已支付
throw new BusinessException(ReturnCodeEnum.CODE_ORDER_IS_NOT_TO_BE_PAID_ERROR);
}
String orderCode = orderInfo.getOrderCode();
// 该订单充电金额
BigDecimal chargeAmount = dto.getPayAmount();
// 记录支付流水
List<OrderPayRecord> payRecordList = Lists.newArrayList();
if (StringUtils.equals(dto.getPayMode(), OrderPayModeEnum.PAYMENT_OF_BALANCE.getValue())) { // 余额支付
// 查询该会员的余额
MemberVO memberVO = memberService.getMemberInfoByMemberId(dto.getMemberId());
BigDecimal totalAccountAmount = memberVO.getTotalAccountAmount();
if (totalAccountAmount.compareTo(chargeAmount) < 0) {
// 总余额小于充电金额
throw new BusinessException(ReturnCodeEnum.CODE_BALANCE_IS_INSUFFICIENT);
}
BigDecimal principalAmount = memberVO.getPrincipalBalance(); // 会员剩余本金金额
BigDecimal giftAmount = memberVO.getGiftBalance(); // 会员剩余赠送余额
BigDecimal principalPay = null; // 30
BigDecimal giftPay = null; // 10
// 先扣除本金金额,再扣除赠送金额
BigDecimal subtract = principalAmount.subtract(chargeAmount);
if (subtract.compareTo(BigDecimal.ZERO) >= 0) {
principalPay = chargeAmount;
} else {
if (principalAmount.compareTo(BigDecimal.ZERO) > 0) {
principalPay = principalAmount;
}
giftPay = subtract.negate();
}
// 更新会员钱包
UpdateMemberBalanceDTO updateMemberBalanceDTO = UpdateMemberBalanceDTO.builder()
.memberId(dto.getMemberId())
.type(MemberWalletEnum.TYPE_OUT.getValue())
.subType(MemberWalletEnum.SUBTYPE_PAYMENT_FOR_ORDER.getValue())
.updatePrincipalBalance(principalPay)
.updateGiftBalance(giftPay)
.relatedOrderCode(orderCode)
.build();
memberBasicInfoService.updateMemberBalance(updateMemberBalanceDTO);
// 记录流水
if (principalPay != null) {
payRecordList.add(OrderPayRecord.builder()
.orderCode(dto.getOrderCode())
.payMode(OrderPayRecordEnum.PRINCIPAL_BALANCE_PAYMENT.getValue())
.payAmount(principalPay)
.createBy(dto.getMemberId())
.build());
}
if (giftPay != null) {
payRecordList.add(OrderPayRecord.builder()
.orderCode(dto.getOrderCode())
.payMode(OrderPayRecordEnum.GIFT_BALANCE_PAYMENT.getValue())
.payAmount(giftPay)
.createBy(dto.getMemberId())
.build());
}
// 余额支付可以直接调支付回调方法
PayOrderSuccessCallbackDTO callbackDTO = PayOrderSuccessCallbackDTO.builder()
.orderCode(orderCode)
.payAmount(chargeAmount)
.payMode(dto.getPayMode())
.build();
payOrderSuccessCallback(callbackDTO);
// 余额支付订单 记录会员交易流水
MemberTransactionRecord record = MemberTransactionRecord.builder()
.orderCode(orderCode)
.scenarioType(ScenarioEnum.ORDER.getValue())
.memberId(memberVO.getMemberId())
.actionType(ActionTypeEnum.FORWARD.getValue())
.payMode(PayModeEnum.PAYMENT_OF_BALANCE.getValue())
.amount(dto.getPayAmount()) // 单位元
.build();
memberTransactionRecordService.insertSelective(record);
} else if (StringUtils.equals(dto.getPayMode(), OrderPayModeEnum.PAYMENT_OF_WECHATPAY.getValue())) { // 微信支付
String openId = memberService.getOpenIdByCode(dto.getCode());
if (StringUtils.isBlank(openId)) {
throw new BusinessException(ReturnCodeEnum.CODE_GET_OPEN_ID_BY_CODE_ERROR);
}
WeixinPayDTO weixinPayDTO = new WeixinPayDTO();
weixinPayDTO.setOpenId(openId);
weixinPayDTO.setAmount(dto.getPayAmount().toString());
// 支付订单 附加参数
PaymentScenarioDTO paymentScenarioDTO = PaymentScenarioDTO.builder()
.type(ScenarioEnum.ORDER.getValue())
.orderCode(dto.getOrderCode())
.memberId(orderInfo.getMemberId())
.build();
weixinPayDTO.setAttach(JSONObject.toJSONString(paymentScenarioDTO));
weixinPayDTO.setDescription("充电费用");
Map<String, Object> weixinMap = this.weixinPayV3(weixinPayDTO);
// 返回微信支付参数
resultMap.put("weixinMap", weixinMap);
} else if (StringUtils.equals(dto.getPayMode(), OrderPayModeEnum.PAYMENT_OF_ALIPAY.getValue())) { // 支付宝支付
// TODO 返回支付宝支付参数
}
// 订单支付流水入库
if (CollectionUtils.isNotEmpty(payRecordList)) {
orderPayRecordService.batchInsert(payRecordList);
}
return resultMap;
}
/**
* 订单支付成功 支付回调
* 支付成功后掉用这个方法
* 1. 修改订单支付状态
* 2. 发送启动充电指令
*/
public void payOrderSuccessCallback(PayOrderSuccessCallbackDTO dto) {
OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByOrderCode(dto.getOrderCode());
BigDecimal payAmount = dto.getPayAmount();
// 修改订单
orderInfo.setPayMode(dto.getPayMode());
orderInfo.setPayStatus("1");
orderInfo.setPayAmount(payAmount);
orderInfo.setPayTime(new Date());
orderBasicInfoService.updateOrderBasicInfo(orderInfo);
// 发送启动指令
StartChargingCommand startChargingCommand = StartChargingCommand.builder()
.pileSn(orderInfo.getPileSn())
.connectorCode(orderInfo.getConnectorCode())
.orderCode(dto.getOrderCode())
.chargeAmount(payAmount)
.build();
ykcPushCommandService.pushStartChargingCommand(startChargingCommand);
}
/**
* 保存订单信息到数据库
*
* @param dto
* @return
*/
private String saveOrder2Database(GenerateOrderDTO dto) {
String orderCode = IdUtils.generateOrderCode(dto.getPileSn(), dto.getConnectorCode());
// 订单基本信息
OrderBasicInfo orderBasicInfo = OrderBasicInfo.builder()
.orderCode(orderCode)
.orderStatus(OrderStatusEnum.NOT_START.getValue())
.memberId(dto.getMemberId())
.stationId(dto.getPileConnector().getStationId())
.pileSn(dto.getPileSn())
.connectorCode(dto.getConnectorCode())
.pileConnectorCode(dto.getPileSn() + dto.getConnectorCode())
.startMode(dto.getStartMode())
.payStatus(Constants.ZERO)
.payAmount(dto.getChargeAmount())
.payMode(dto.getPayMode())
.orderAmount(BigDecimal.ZERO)
.build();
// 订单详情
OrderDetail orderDetail = OrderDetail.builder()
.orderCode(orderCode)
.sharpElectricityPrice(dto.getBillingTemplate().getSharpElectricityPrice())
.sharpServicePrice(dto.getBillingTemplate().getSharpServicePrice())
.peakElectricityPrice(dto.getBillingTemplate().getPeakElectricityPrice())
.peakServicePrice(dto.getBillingTemplate().getPeakServicePrice())
.flatElectricityPrice(dto.getBillingTemplate().getFlatElectricityPrice())
.flatServicePrice(dto.getBillingTemplate().getFlatServicePrice())
.valleyElectricityPrice(dto.getBillingTemplate().getValleyElectricityPrice())
.valleyServicePrice(dto.getBillingTemplate().getValleyServicePrice())
.build();
OrderTransactionDTO createOrderTransactionDTO = OrderTransactionDTO.builder()
.orderBasicInfo(orderBasicInfo)
.orderDetail(orderDetail)
.build();
pileTransactionService.doCreateOrder(createOrderTransactionDTO);
return orderCode;
}
/**
* 校验充电桩相关的信息
*
* @param dto
*/
private void checkPileInfo(GenerateOrderDTO dto) {
// 查询充电桩状态 是否空闲 枪口是否占用
PileConnectorDetailVO pileConnector = pileService.queryPileConnectorDetail(dto.getPileSn() + dto.getConnectorCode());
if (pileConnector == null) {
log.error("checkPileInfo充电枪口为空 pileSn:{}, connectorCode:{}", dto.getPileSn(), dto.getConnectorCode());
throw new BusinessException(ReturnCodeEnum.CODE_CONNECTOR_INFO_NULL_ERROR);
}
// 判断枪口状态
if (!(StringUtils.equals(pileConnector.getConnectorStatus(), PileConnectorDataBaseStatusEnum.FREE.getValue())
|| StringUtils.equals(pileConnector.getConnectorStatus(), PileConnectorDataBaseStatusEnum.OCCUPIED_NOT_CHARGED.getValue()))) {
log.error("checkPileInfo充电枪口状态不正确当前状态为:{}", pileConnector.getConnectorStatus());
throw new BusinessException(ReturnCodeEnum.CODE_PILE_CONNECTOR_STATUS_ERROR);
}
// 查询充电桩的计费模板
BillingTemplateVO billingTemplateVO = pileBillingTemplateService.selectBillingTemplateDetailByPileSn(dto.getPileSn());
if (billingTemplateVO == null) {
throw new BusinessException(ReturnCodeEnum.CODE_BILLING_TEMPLATE_NULL_ERROR);
}
dto.setPileConnector(pileConnector);
dto.setBillingTemplate(billingTemplateVO);
}
/**
* 处理前端传的参数
* pileConnectorCode = pileSn + connectorCode
*
* @param dto
*/
public void analysisPileParameter(BasicPileDTO dto) {
if (StringUtils.isBlank(dto.getPileSn()) || StringUtils.isBlank(dto.getConnectorCode())) {
// 从pileConnectorCode解析
String pileConnectorCode = dto.getPileConnectorCode();
if (StringUtils.isNotEmpty(pileConnectorCode) && pileConnectorCode.length() == Constants.PILE_CONNECTOR_CODE_LENGTH) {
dto.setPileSn(StringUtils.substring(pileConnectorCode, 0, pileConnectorCode.length() - 2));
dto.setConnectorCode(StringUtils.substring(pileConnectorCode, pileConnectorCode.length() - 2, pileConnectorCode.length()));
} else {
throw new BusinessException(ReturnCodeEnum.CODE_DATA_LENGTH_ERROR);
}
} else {
// 说明pileSn 和 connectorCode前端传了那就校验一下长度
if (dto.getPileSn().length() != Constants.PILE_SN_LENGTH || dto.getConnectorCode().length() != Constants.CONNECTOR_CODE_LENGTH) {
throw new BusinessException(ReturnCodeEnum.CODE_DATA_LENGTH_ERROR);
}
}
}
/**
* 结算订单
* endCharging
*
* @param dto 结算订单参数
*/
public void settleOrderForWeb(SettleOrderDTO dto) {
analysisPileParameter(dto);
// 查询订单详情,验证订单中的桩编号是否正确
OrderBasicInfo orderBasicInfo = orderBasicInfoService.getOrderInfoByOrderCode(dto.getOrderCode());
if (orderBasicInfo == null) {
throw new BusinessException(ReturnCodeEnum.CODE_QUERY_ORDER_NULL_ERROR);
}
if (!(StringUtils.equals(orderBasicInfo.getPileSn(), dto.getPileSn())
&& StringUtils.equals(orderBasicInfo.getConnectorCode(), dto.getConnectorCode()))) {
throw new BusinessException(ReturnCodeEnum.CODE_ORDER_PILE_MAPPING_ERROR);
}
// push远程停机指令
pileRemoteService.remoteStopCharging(dto.getPileSn(), dto.getConnectorCode());
// 桩计算的消费金额
// 对比一下,是否需要退款
}
/**
* 通过会员Id查询订单列表
*
* @param memberId 会员Id
* @return 订单信息集合
*/
public PageResponse getListByMemberIdAndOrderStatus(String memberId, UniAppQueryOrderDTO dto) throws ParseException {
String orderStatus = dto.getOrderStatus();
if (StringUtils.isBlank(orderStatus)) {
throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
}
ArrayList<String> orderStatusList = Lists.newArrayList();
if (StringUtils.equals("2", orderStatus)) {
// 查未完成订单
CollectionUtils.addAll(orderStatusList, "0", "1", "2", "3", "4", "5");
} else if (StringUtils.equals("3", orderStatus)) {
// 查已完成订单
orderStatusList.add("6");
}
// 分页
PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
List<OrderVO> list = orderBasicInfoService.getListByMemberIdAndOrderStatus(memberId, orderStatusList);
PageInfo<OrderVO> pageInfo = new PageInfo<>(list);
for (OrderVO orderVO : pageInfo.getList()) {
orderVO.setPileConnectorCode(orderVO.getPileSn() + orderVO.getConnectorCode());
Date endTimeDate;
Date startTimeDate = sdf.parse(orderVO.getStartTime());
if (StringUtils.isNotBlank(orderVO.getEndTime())) {
endTimeDate = sdf.parse(orderVO.getEndTime());
} else {
endTimeDate = new Date();
}
// 计算出两个时间差
orderVO.setChargingTime(DateUtils.getDatePoor(endTimeDate, startTimeDate));
}
// 返回结果集
PageResponse pageResponse = PageResponse.builder()
.pageNum(dto.getPageNum())
.pageSize(dto.getPageSize())
.list(pageInfo.getList())
.pages(pageInfo.getPages())
.total(pageInfo.getTotal())
.build();
return pageResponse;
}
/**
* 微信支付v3
*
* @param dto
* @return
* @throws Exception
*/
public Map<String, Object> weixinPayV3(WeixinPayDTO dto) throws Exception {
return wechatPayService.weixinPayV3(dto);
}
/**
* 用户停止充电
*
* @param dto
*/
public void stopCharging(StopChargingDTO dto) {
// 查订单
OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByOrderCode(dto.getOrderCode());
if (orderInfo == null) {
throw new BusinessException(ReturnCodeEnum.CODE_QUERY_ORDER_NULL_ERROR);
}
// 校验订单中的会员与操作会员是否一致
if (!StringUtils.equals(orderInfo.getMemberId(), dto.getMemberId())) {
throw new BusinessException(ReturnCodeEnum.CODE_ORDER_MEMBER_NOT_MATCH_ERROR);
}
// 发送停止指令
pileRemoteService.remoteStopCharging(orderInfo.getPileSn(), orderInfo.getConnectorCode());
log.info("订单号:{}发送停机指令成功", dto.getOrderCode());
}
/**
* 微信支付回调
*
* @param request
* @param body
* @throws Exception
*/
public void wechatPayCallback(HttpServletRequest request, WechatPayNotifyParameter body) throws Exception {
// 获取微信支付成功返回的信息
Map<String, Object> map = wechatPayService.wechatPayCallbackInfo(request, body);
String type = (String) map.get("type");
BigDecimal amount = (BigDecimal) map.get("amount"); // 微信给的amount单位是分
amount = amount.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP); // 转换为元
String orderCode = (String) map.get("orderCode");
String memberId = (String) map.get("memberId");
if (StringUtils.equals(type, ScenarioEnum.ORDER.getValue())) { // 1-订单支付
// 支付订单成功
// orderCode = (String) map.get("orderCode");
PayOrderSuccessCallbackDTO callbackDTO = PayOrderSuccessCallbackDTO.builder()
.orderCode(orderCode)
.payAmount(amount)
.payMode(OrderPayModeEnum.PAYMENT_OF_WECHATPAY.getValue())
.build();
// 订单支付成功 支付回调
payOrderSuccessCallback(callbackDTO);
// 记录订单支付流水
OrderPayRecord orderPayRecord = OrderPayRecord.builder()
.orderCode(orderCode)
.payMode(OrderPayRecordEnum.WECHATPAY_PAYMENT.getValue())
.payAmount(amount)
.createBy(null)
.build();
orderPayRecordService.batchInsert(Lists.newArrayList(orderPayRecord));
} else if (StringUtils.equals(type, ScenarioEnum.BALANCE.getValue())) { // 2-充值余额
// 充值余额成功
// memberId = (String) map.get("memberId");
UpdateMemberBalanceDTO dto = new UpdateMemberBalanceDTO();
dto.setMemberId(memberId);
dto.setType(MemberWalletEnum.TYPE_IN.getValue());
dto.setSubType(MemberWalletEnum.SUBTYPE_TOP_UP.getValue());
dto.setUpdatePrincipalBalance(amount);
memberBasicInfoService.updateMemberBalance(dto);
}
// 微信支付订单 记录会员交易流水
MemberTransactionRecord record = MemberTransactionRecord.builder()
.orderCode(orderCode)
.scenarioType(type)
.memberId(memberId)
.actionType(ActionTypeEnum.FORWARD.getValue())
.payMode(PayModeEnum.PAYMENT_OF_WECHATPAY.getValue())
.amount(amount) // 单位元
.outTradeNo(String.valueOf(map.get("out_trade_no")))
.transactionId(String.valueOf(map.get("transaction_id")))
.build();
memberTransactionRecordService.insertSelective(record);
}
public void weChatRefund(WeChatRefundDTO dto) {
log.info("微信退款接口 param:{}", JSONObject.toJSONString(dto));
orderBasicInfoService.weChatRefund(dto);
}
/**
* 查询订单详情信息
* @param orderCode 订单编号
* @return
*/
public OrderDetailInfoVO queryOrderDetailInfo(String orderCode) {
OrderDetailInfoVO vo = new OrderDetailInfoVO();
// 订单信息
OrderBasicInfo orderBasicInfo = orderBasicInfoService.getOrderInfoByOrderCode(orderCode);
if (orderBasicInfo == null) {
return vo;
}
OrderDetailInfoVO.OrderInfo order = new OrderDetailInfoVO.OrderInfo();
order.setOrderCode(orderBasicInfo.getOrderCode());
order.setOrderStatus(orderBasicInfo.getOrderStatus());
order.setStartTime(DateUtils.formatDateTime(orderBasicInfo.getChargeStartTime()));
order.setEndTime(DateUtils.formatDateTime(orderBasicInfo.getChargeEndTime()));
order.setCreateTime(DateUtils.formatDateTime(orderBasicInfo.getCreateTime()));
order.setStopReasonMsg(orderBasicInfo.getReason());
order.setStartSOC(orderBasicInfo.getStartSOC());
order.setEndSOC(orderBasicInfo.getEndSOC());
vo.setOrderInfo(order);
// 设备信息
PileInfoVO pileInfoVO = pileService.selectPileInfoBySn(orderBasicInfo.getPileSn());
vo.setPileInfo(pileInfoVO);
// 枪口实时数据信息
String pileConnectorCode = orderBasicInfo.getPileSn() + orderBasicInfo.getConnectorCode();
QueryConnectorListDTO dto = new QueryConnectorListDTO();
dto.setConnectorCodeList(Lists.newArrayList(pileConnectorCode));
List<RealTimeMonitorData> chargingRealTimeDataList = orderBasicInfoService.getChargingRealTimeData(orderCode);
if (CollectionUtils.isNotEmpty(chargingRealTimeDataList)) {
List<OrderDetailInfoVO.RealTimeMonitorData> infoList = Lists.newArrayList();
for (RealTimeMonitorData realTimeMonitorData : chargingRealTimeDataList) {
OrderDetailInfoVO.RealTimeMonitorData info = new OrderDetailInfoVO.RealTimeMonitorData();
info.setInstantCurrent(realTimeMonitorData.getOutputCurrent()); // 电流
info.setInstantVoltage(realTimeMonitorData.getOutputVoltage()); // 电压
info.setInstantPower(realTimeMonitorData.getOutputPower()); // 功率
info.setSOC(realTimeMonitorData.getSOC());
info.setTime(realTimeMonitorData.getDateTime()); // 时间
infoList.add(info);
}
// 监控信息
OrderDetailInfoVO.OrderRealTimeInfo realTimeInfo = new OrderDetailInfoVO.OrderRealTimeInfo();
RealTimeMonitorData realTimeMonitorData = chargingRealTimeDataList.get(0);
realTimeInfo.setOrderAmount(realTimeMonitorData.getChargingAmount());
// realTimeInfo.setTotalElectricityAmount();
// realTimeInfo.setTotalServiceAmount();
realTimeInfo.setChargedDegree(realTimeMonitorData.getChargingDegree());
// realTimeInfo.setSOC(realTimeMonitorData.getSOC());
realTimeInfo.setChargingTime(realTimeMonitorData.getSumChargingTime());
vo.setOrderRealTimeInfo(realTimeInfo);
// 根据时间进行正序排序
infoList = infoList.stream()
.sorted(Comparator.comparing(OrderDetailInfoVO.RealTimeMonitorData::getTime))
.collect(Collectors.toList());
vo.setRealTimeMonitorDataList(infoList);
}
// 支付流水
List<OrderPayRecord> orderPayRecordList = orderPayRecordService.getOrderPayRecordList(orderCode);
if (CollectionUtils.isNotEmpty(orderPayRecordList)) {
OrderPayRecord orderPayRecord = orderPayRecordList.get(0);
List<OrderDetailInfoVO.PayRecord> payRecordList = Lists.newArrayList();
OrderDetailInfoVO.PayRecord payInfo = new OrderDetailInfoVO.PayRecord();
// 余额支付如果是由本金和赠送一起支付的,合并为一个
BigDecimal bigDecimal = orderPayRecordList.stream()
.map(OrderPayRecord::getPayAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
payInfo.setPayAmount(bigDecimal.toString());
payInfo.setPayStatus(orderBasicInfo.getPayStatus());
payInfo.setPayTime(DateUtils.formatDateTime(orderBasicInfo.getPayTime()));
String payMode = orderPayRecord.getPayMode();
if (StringUtils.equals(payMode, OrderPayRecordEnum.PRINCIPAL_BALANCE_PAYMENT.getValue())
|| StringUtils.equals(payMode, OrderPayRecordEnum.GIFT_BALANCE_PAYMENT.getValue())) {
// 使用余额支付
payInfo.setPayMode(OrderPayModeEnum.PAYMENT_OF_BALANCE.getValue());
payInfo.setPayModeDesc(OrderPayModeEnum.PAYMENT_OF_BALANCE.getLabel());
} else if (StringUtils.equals(payMode, OrderPayRecordEnum.WECHATPAY_PAYMENT.getValue())){
// 使用微信支付
payInfo.setPayMode(OrderPayModeEnum.PAYMENT_OF_WECHATPAY.getValue());
payInfo.setPayModeDesc(OrderPayModeEnum.PAYMENT_OF_WECHATPAY.getLabel());
// 查微信支付回调记录
WxpayCallbackRecord wxpayCallbackRecord = wxpayCallbackRecordService.selectByOrderCode(orderCode);
if (wxpayCallbackRecord != null) {
payInfo.setOutTradeNo(wxpayCallbackRecord.getOutTradeNo());
payInfo.setTransactionId(wxpayCallbackRecord.getTransactionId());
}
} else if (StringUtils.equals(payMode, OrderPayRecordEnum.WHITELIST_PAYMENT.getValue())){
// 使用白名单支付
payInfo.setPayMode(OrderPayModeEnum.PAYMENT_OF_WHITELIST.getValue());
payInfo.setPayModeDesc(OrderPayModeEnum.PAYMENT_OF_WHITELIST.getLabel());
}
payRecordList.add(payInfo);
vo.setPayRecordList(payRecordList);
}
// 用户信息
MemberVO memberVO = memberService.getMemberInfoByMemberId(orderBasicInfo.getMemberId());
vo.setMemberInfo(memberVO);
return vo;
}
public void wechatPayRefundCallback(HttpServletRequest request, WechatPayNotifyParameter body) throws Exception {
// 获取微信退款成功返回的信息
Map<String, Object> map = wechatPayService.wechatPayRefundCallbackInfo(request, body);
}
/**
* 获取小程序订单详情
* @param orderCode
* @return
*/
public UniAppOrderVO getUniAppOrderDetail(String orderCode) {
OrderBasicInfo orderBasicInfo = orderBasicInfoService.getOrderInfoByOrderCode(orderCode);
if (orderBasicInfo == null) {
throw new BusinessException(ReturnCodeEnum.CODE_QUERY_ORDER_NULL_ERROR);
}
UniAppOrderVO vo = new UniAppOrderVO();
vo.setOrderCode(orderBasicInfo.getOrderCode());
vo.setPileSn(orderBasicInfo.getPileSn());
vo.setConnectorCode(orderBasicInfo.getConnectorCode());
vo.setPileConnectorCode(orderBasicInfo.getPileSn() + orderBasicInfo.getConnectorCode());
String orderStatus = orderBasicInfo.getOrderStatus();
vo.setOrderStatus(orderStatus);
// 订单状态描述
String orderStatusDescribe;
if (StringUtils.equals(orderStatus, OrderStatusEnum.NOT_START.getValue())) {
// 未启动还有两种情况 待支付 / 支付成功
String payStatus = orderBasicInfo.getPayStatus();
if (StringUtils.equals(payStatus, OrderPayStatusEnum.paid.getValue())) {
// 支付成功,未启动
orderStatusDescribe = OrderPayStatusEnum.paid.getLabel() + ", " + OrderStatusEnum.getOrderStatus(orderStatus);
} else {
// 待支付
orderStatusDescribe = OrderPayStatusEnum.unpaid.getLabel();
}
} else {
orderStatusDescribe = OrderStatusEnum.getOrderStatus(orderStatus);
}
vo.setOrderStatusDescribe(orderStatusDescribe);
// 获取充电桩枪口信息
PileConnectorDetailVO pileConnectorDetailVO = pileService.queryPileConnectorDetail(vo.getPileConnectorCode());
if (pileConnectorDetailVO != null) {
vo.setPileConnectorStatus(pileConnectorDetailVO.getConnectorStatus());
}
// 获取订单充电数据
List<RealTimeMonitorData> monitorDataList = orderBasicInfoService.getChargingRealTimeData(orderCode);
if (CollectionUtils.isNotEmpty(monitorDataList)) {
List<UniAppOrderVO.ChargingData> chargingDataList = Lists.newArrayList();
UniAppOrderVO.ChargingData data = null;
for (int i = 0; i < monitorDataList.size(); i++) {
RealTimeMonitorData monitorData = monitorDataList.get(i);
data = new UniAppOrderVO.ChargingData();
data.setDateTime(monitorData.getDateTime());
String outputVoltage = monitorData.getOutputVoltage();
data.setOutputVoltage(outputVoltage);
String outputCurrent = monitorData.getOutputCurrent();
data.setOutputCurrent(outputCurrent);
BigDecimal power = new BigDecimal(outputCurrent).multiply(new BigDecimal(outputVoltage))
.divide(new BigDecimal("1000"), 2, BigDecimal.ROUND_HALF_UP);
data.setPower(power.toString());
data.setSOC(monitorData.getSOC());
data.setBatteryMaxTemperature(monitorData.getBatteryMaxTemperature());
chargingDataList.add(data);
// vo中的实时数据最新一条就取monitorDataList第一个
if (i == 0) {
vo.setBatteryMaxTemperature(data.getBatteryMaxTemperature());
vo.setOutputPower(data.getPower());
vo.setOutputCurrent(data.getOutputCurrent());
vo.setOutputVoltage(data.getOutputVoltage());
vo.setSOC(data.getSOC());
BigDecimal chargingAmount = new BigDecimal(monitorData.getChargingAmount()).setScale(2, BigDecimal.ROUND_HALF_UP); // 充电金额
vo.setChargingAmount(chargingAmount.toString());
BigDecimal chargingDegree = new BigDecimal(monitorData.getChargingDegree()).setScale(2, BigDecimal.ROUND_HALF_UP); // 充电度数
vo.setChargingDegree(chargingDegree.toString());
vo.setSumChargingTime(monitorData.getSumChargingTime());
vo.setTimeRemaining(monitorData.getTimeRemaining());
}
}
// monitorDataList是按照时间倒序的chargingDataList需要按照时间正序
Collections.reverse(chargingDataList);
vo.setChargingDataList(chargingDataList);
}
return vo;
}
/**
* 根据订单号查询充电桩启动状态
* @param orderCode
* @return
*/
public String selectPileStarterStatus(String orderCode) {
List<RealTimeMonitorData> chargingRealTimeData = orderBasicInfoService.getChargingRealTimeData(orderCode);
// 只有充电桩上传的实时数据中的状态为充电,才能查到实时数据列表
return CollectionUtils.isNotEmpty(chargingRealTimeData) ? Constants.ONE : Constants.ZERO;
}
public void closeStartFailedOrder(QueryOrderDTO dto) {
orderBasicInfoService.closeStartFailedOrder(dto.getStartTime(), dto.getEndTime());
}
}

View File

@@ -0,0 +1,203 @@
package com.jsowell.service;
import com.google.common.collect.Lists;
import com.jsowell.common.util.StringUtils;
import com.jsowell.netty.command.ykc.GetRealTimeMonitorDataCommand;
import com.jsowell.netty.command.ykc.IssueQRCodeCommand;
import com.jsowell.netty.command.ykc.ProofreadTimeCommand;
import com.jsowell.netty.command.ykc.PublishPileBillingTemplateCommand;
import com.jsowell.netty.command.ykc.RebootCommand;
import com.jsowell.netty.command.ykc.StartChargingCommand;
import com.jsowell.netty.command.ykc.StopChargingCommand;
import com.jsowell.netty.command.ykc.UpdateFileCommand;
import com.jsowell.netty.service.yunkuaichong.YKCPushCommandService;
import com.jsowell.pile.domain.PileBillingRelation;
import com.jsowell.pile.domain.PileBillingTemplate;
import com.jsowell.pile.dto.PublishBillingTemplateDTO;
import com.jsowell.pile.service.IPileBasicInfoService;
import com.jsowell.pile.service.IPileBillingTemplateService;
import com.jsowell.pile.vo.web.PileDetailVO;
import com.jsowell.pile.vo.web.BillingTemplateVO;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@Service
public class PileRemoteService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private IPileBillingTemplateService pileBillingTemplateService;
@Autowired
private IPileBasicInfoService pileBasicInfoService;
@Autowired
private YKCPushCommandService ykcPushCommandService;
/**
* 获取充电桩实时数据信息
*
* @param pileSn 充电桩sn
* @param connectorCode 枪口号
*/
public void getRealTimeMonitorData(String pileSn, String connectorCode) {
if (StringUtils.isNotEmpty(pileSn) || StringUtils.isNotEmpty(connectorCode)) {
GetRealTimeMonitorDataCommand command = GetRealTimeMonitorDataCommand.builder()
.pileSn(pileSn)
.connectorCode(connectorCode)
.build();
ykcPushCommandService.pushGetRealTimeMonitorDataCommand(command);
}
}
/**
* 重启指令
*
* @param pileSn 充电桩sn
*/
public void reboot(String pileSn) {
RebootCommand command = RebootCommand.builder().pileSn(pileSn).build();
ykcPushCommandService.pushRebootCommand(command);
}
/**
* 远程启动充电 0x34
*
* @param pileSn 充电桩sn
*/
// public void remoteStartCharging(String orderCode, String pileSn, String connectorCode, BigDecimal accountBalance) {
// // String s = "550314127823050120180619144446808800000000000101000000100000057300000000D14B0A54A0860100";
// if (StringUtils.isEmpty(pileSn) || StringUtils.isEmpty(connectorCode)) {
// log.warn("远程启动充电, 充电桩编号和枪口号不能为空");
// return;
// }
// log.info("=====平台下发指令=====: 远程启动充电, 桩号:{}, 枪口号:{}", pileSn, connectorCode);
// StartChargingCommand startChargingCommand = StartChargingCommand.builder()
// .pileSn(pileSn)
// .connectorCode(connectorCode)
// .orderCode(orderCode)
// .chargeAmount(accountBalance)
// .build();
// ykcPushCommandService.pushStartChargingCommand(startChargingCommand);
// }
/**
* 远程停止充电
*/
public void remoteStopCharging(String pileSn, String connectorCode) {
StopChargingCommand command = StopChargingCommand.builder()
.pileSn(pileSn)
.connectorCode(connectorCode)
.build();
ykcPushCommandService.pushStopChargingCommand(command);
}
/**
* 下发充电桩二维码
*
* @param pileSn 充电桩sn
*/
public void issueQRCode(String pileSn) {
IssueQRCodeCommand command = IssueQRCodeCommand.builder().pileSn(pileSn).build();
ykcPushCommandService.pushIssueQRCodeCommand(command);
}
/**
* 充电桩对时
*
* @param pileSn 充电桩sn
*/
public void proofreadTime(String pileSn) {
ProofreadTimeCommand command = ProofreadTimeCommand.builder().pileSn(pileSn).build();
ykcPushCommandService.pushProofreadTimeCommand(command);
}
/**
* 下发充电桩计费模型
*/
public void publishPileBillingTemplate(String pileSn, BillingTemplateVO billingTemplateVO) {
PublishPileBillingTemplateCommand command = PublishPileBillingTemplateCommand.builder()
.billingTemplateVO(billingTemplateVO)
.pileSn(pileSn)
.build();
ykcPushCommandService.pushPublishPileBillingTemplate(command);
}
/**
* 下发计费模板
* @param dto
* @return
*/
public boolean publishBillingTemplate(PublishBillingTemplateDTO dto) {
// 获取计费模板信息
BillingTemplateVO billingTemplateVO = pileBillingTemplateService.selectBillingTemplateByTemplateId(dto.getTemplateId());
if (billingTemplateVO == null) {
log.warn("获取计费模板信息, 通过模板id:{}查询计费模板为null", dto.getTemplateId());
return false;
}
// 更新计费模板的发布时间
PileBillingTemplate pileBillingTemplate = new PileBillingTemplate();
pileBillingTemplate.setId(Long.valueOf(billingTemplateVO.getTemplateId()));
pileBillingTemplate.setPublishTime(new Date());
pileBillingTemplateService.updatePileBillingTemplate(pileBillingTemplate);
// 获取到站点下所有的桩
List<PileDetailVO> pileList = pileBasicInfoService.selectPileListByStationIds(Lists.newArrayList(Long.valueOf(dto.getStationId())));
if (CollectionUtils.isEmpty(pileList)) {
log.warn("获取到站点下所有的桩, 通过站点id:{}查询充电桩列表为空", dto.getStationId());
return false;
}
// 保存计费模板和桩的关系
List<PileBillingRelation> relationList = Lists.newArrayList();
for (PileDetailVO pileInfoVO : pileList) {
// push
publishPileBillingTemplate(pileInfoVO.getPileSn(), billingTemplateVO);
// 入库
relationList.add(PileBillingRelation.builder()
.pileSn(pileInfoVO.getPileSn())
.billingTemplateCode(billingTemplateVO.getTemplateCode())
.stationId(dto.getStationId())
.build());
}
if (CollectionUtils.isNotEmpty(relationList)) {
pileBillingTemplateService.insertPileBillingRelation(relationList);
}
return true;
}
public static void main(String[] args) {
/*Date date = new Date();
String encodeCP56Time2a = DateUtils.encodeCP56Time2a(date);
System.out.println(encodeCP56Time2a);
System.out.println(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, date));
String decodeCP56Time2a = DateUtils.decodeCP56Time2a(encodeCP56Time2a);
System.out.println(decodeCP56Time2a);*/
}
/**
* 远程更新
*
* @param pileSns 前台传的桩号集合
*/
public void updateFile(List<String> pileSns) {
//
UpdateFileCommand command = UpdateFileCommand.builder().pileSnList(pileSns).build();
ykcPushCommandService.pushUpdateFileCommand(command);
}
}

View File

@@ -0,0 +1,438 @@
package com.jsowell.service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.ykc.RealTimeMonitorData;
import com.jsowell.common.core.page.PageResponse;
import com.jsowell.common.enums.ykc.BusinessTypeEnum;
import com.jsowell.common.enums.ykc.OrderStatusEnum;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.common.util.DateUtils;
import com.jsowell.common.util.SecurityUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.id.SnUtils;
import com.jsowell.pile.domain.*;
import com.jsowell.pile.dto.BatchCreatePileDTO;
import com.jsowell.pile.dto.MemberRegisterAndLoginDTO;
import com.jsowell.pile.dto.PileMemberBindingDTO;
import com.jsowell.pile.dto.QueryPersonPileDTO;
import com.jsowell.pile.service.*;
import com.jsowell.pile.transaction.dto.PileTransactionDTO;
import com.jsowell.pile.transaction.service.TransactionService;
import com.jsowell.pile.vo.base.ConnectorInfoVO;
import com.jsowell.pile.vo.base.MerchantInfoVO;
import com.jsowell.pile.vo.base.PileInfoVO;
import com.jsowell.pile.vo.uniapp.*;
import com.jsowell.pile.vo.web.PileStationVO;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
@Service
public class PileService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private TransactionService pileTransactionService;
@Resource
private SnUtils snUtils;
@Autowired
private IPileBasicInfoService pileBasicInfoService;
@Autowired
private IPileConnectorInfoService pileConnectorInfoService;
@Autowired
private IPileStationInfoService pileStationInfoService;
@Autowired
private IPileMerchantInfoService pileMerchantInfoService;
@Autowired
private IPileBillingTemplateService pileBillingTemplateService;
@Autowired
private IPileMemberRelationService pileMemberRelationService;
@Autowired
private IMemberBasicInfoService memberBasicInfoService;
@Autowired
private MemberService memberService;
@Autowired
private IOrderBasicInfoService orderBasicInfoService;
/**
* 查询设备信息
*
* @param pileConnectorCode 充电枪编号 880000000000000101
* @return 设备信息集合
*/
public PileConnectorDetailVO queryPileConnectorDetail(String pileConnectorCode) {
return pileBasicInfoService.queryPileConnectorDetail(pileConnectorCode);
}
/**
* 查询设备信息
*
* @param pileSn 充电枪编号 8800000000000001
* @param connectorCode 充电枪口号 01
* @return 设备信息集合
*/
public PileConnectorDetailVO queryPileConnectorDetail(String pileSn, String connectorCode) {
return queryPileConnectorDetail(pileSn + connectorCode);
}
public int batchCreatePile(BatchCreatePileDTO dto) {
// 批量生成sn号
List<String> snList = snUtils.generateSN(dto.getNum());
//
List<PileBasicInfo> basicInfoList = Lists.newArrayList();
List<PileConnectorInfo> connectorInfoList = Lists.newArrayList();
PileBasicInfo basicInfo = null;
PileConnectorInfo connectorInfo = null;
for (String sn : snList) {
// 组装pile_basic_info表数据
basicInfo = new PileBasicInfo();
basicInfo.setSn(sn); // sn号
basicInfo.setBusinessType(BusinessTypeEnum.OPERATING_PILE.getValue()); // 经营类型 默认运营桩
basicInfo.setSoftwareProtocol(dto.getSoftwareProtocol()); // 软件协议
basicInfo.setMerchantId(Long.valueOf(dto.getMerchantId())); // 运营商id
basicInfo.setStationId(Long.valueOf(dto.getStationId())); // 站点id
basicInfo.setModelId(Long.valueOf(dto.getModelId())); // 型号id
basicInfo.setProductionDate(dto.getProductionDate()); // 生产日期
basicInfo.setLicenceId(null); // TODO 证书编号
basicInfo.setSimId(null); // TODO sim卡
basicInfo.setRemark(dto.getRemark()); // 备注
basicInfo.setCreateBy(SecurityUtils.getUsername()); // 创建人
basicInfo.setDelFlag(Constants.DEL_FLAG_NORMAL); // 删除标识
basicInfoList.add(basicInfo);
for (int i = 1; i < dto.getConnectorNum() + 1; i++) {
// 组装pile_connector_info表数据
connectorInfo = new PileConnectorInfo();
connectorInfo.setPileSn(sn); // sn号
String connectorCode = String.format("%1$02d", i);
connectorInfo.setPileConnectorCode(sn + connectorCode); // 枪口号
connectorInfo.setStatus(Constants.ZERO); //状态,默认 0-离网
connectorInfo.setCreateBy(SecurityUtils.getUsername()); // 创建人
connectorInfo.setDelFlag(Constants.DEL_FLAG_NORMAL); // 删除标识
connectorInfoList.add(connectorInfo);
}
}
// 批量入库
PileTransactionDTO transactionDTO = PileTransactionDTO.builder()
.pileBasicInfoList(basicInfoList)
.pileConnectorInfoList(connectorInfoList)
.build();
return pileTransactionService.doCreatePileTransaction(transactionDTO);
}
/**
* 前端扫码跳转接口
*/
public PileConnectorVO getPileDetailByPileSn(String param) throws ExecutionException, InterruptedException {
if (StringUtils.isBlank(param)) {
throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
}
String pileSn;
if (param.length() == 16) {
pileSn = StringUtils.substring(param, 0, param.length() - 2);
} else {
pileSn = param;
}
// 查询充电桩信息
PileInfoVO pileInfoVO = pileBasicInfoService.selectPileInfoBySn(pileSn);
if (pileInfoVO == null) {
return null;
}
// 查询充电桩下枪口信息
CompletableFuture<List<ConnectorInfoVO>> connectorInfoListFuture = CompletableFuture.supplyAsync(() -> pileConnectorInfoService.selectConnectorInfoList(pileSn));
// 查计费模板信息
CompletableFuture<List<BillingPriceVO>> billingPriceFuture = CompletableFuture.supplyAsync(() -> pileBillingTemplateService.queryBillingPrice(pileInfoVO.getStationId()));
// 查询站点信息
CompletableFuture<PileStationVO> pileStationVOFuture = CompletableFuture.supplyAsync(() -> pileStationInfoService.getStationInfo(pileInfoVO.getStationId()));
// 查询运营商信息
CompletableFuture<MerchantInfoVO> merchantInfoVOFuture = CompletableFuture.supplyAsync(() -> pileMerchantInfoService.getMerchantInfo(pileInfoVO.getMerchantId()));
CompletableFuture<Void> all = CompletableFuture.allOf(connectorInfoListFuture, pileStationVOFuture, merchantInfoVOFuture, billingPriceFuture);
// .join()和.get()都会阻塞并获取线程的执行情况
// .join()会抛出未经检查的异常,不会强制开发者处理异常 .get()会抛出检查异常,需要开发者处理
all.join();
all.get();
List<ConnectorInfoVO> connectorInfoList = connectorInfoListFuture.get();
PileStationVO pileStationVO = pileStationVOFuture.get();
MerchantInfoVO merchantInfoVO = merchantInfoVOFuture.get();
List<BillingPriceVO> billingPriceVOS = billingPriceFuture.get();
PileConnectorVO vo = PileConnectorVO.builder()
.pileInfo(pileInfoVO)
.connectorInfoList(connectorInfoList)
.merchantInfo(merchantInfoVO)
.stationInfo(pileStationVO)
.billingPriceList(billingPriceVOS)
.build();
return vo;
}
public PileConnectorVO getConnectorDetail(String pileConnectorCode) throws ExecutionException, InterruptedException {
PileConnectorDetailVO pileConnectorDetailVO = queryPileConnectorDetail(pileConnectorCode);
if (pileConnectorDetailVO == null) {
return null;
}
String pileSn = pileConnectorDetailVO.getPileSn();
PileConnectorVO resultVO = getPileDetailByPileSn(pileSn);
List<ConnectorInfoVO> connectorInfoList = resultVO.getConnectorInfoList();
if (connectorInfoList.size() > 1) {
List<ConnectorInfoVO> list = Lists.newArrayList();
// 枪口大于1个此充电桩非单枪设备根据参数展示对应枪口的信息
for (ConnectorInfoVO connectorInfoVO : connectorInfoList) {
if (StringUtils.equals(pileConnectorCode, pileSn + connectorInfoVO.getConnectorCode())) {
list.add(connectorInfoVO);
}
}
resultVO.setConnectorInfoList(list);
}
return resultVO;
}
public PileInfoVO selectPileInfoBySn(String pileSn) {
return pileBasicInfoService.selectPileInfoBySn(pileSn);
}
/**
* 用户绑定个人桩
*
* @param dto
* @return
*/
public int pileMemberBinding(PileMemberBindingDTO dto){
// 校验短信验证码
MemberRegisterAndLoginDTO registerAndLoginDTO = MemberRegisterAndLoginDTO.builder()
.mobileNumber(dto.getPhoneNumber())
.verificationCode(dto.getVerificationCode())
.build();
memberService.checkVerificationCode(registerAndLoginDTO);
// 检查桩是否已经被绑定
PileMemberRelation pileMemberRelation = new PileMemberRelation();
pileMemberRelation.setPileSn(dto.getPileSn());
List<PileMemberRelation> list = pileMemberRelationService.selectPileMemberRelationList(pileMemberRelation);
if (CollectionUtils.isNotEmpty(list)){
// 说明已经被绑定过,抛出异常
throw new BusinessException(ReturnCodeEnum.CODE_PILE_HAS_BEEN_BINDING_ERROR);
}
// 如果没被绑定,则此用户为管理员
pileMemberRelation.setMemberId(dto.getMemberId());
pileMemberRelation.setType("1"); // 1-管理员
return pileMemberRelationService.insertPileMemberRelation(pileMemberRelation);
}
/**
* 个人桩管理员下发给其他用户使用
*
* @param dto
*/
public void adminIssuePile(PileMemberBindingDTO dto) {
List<PileMemberRelation> relationList = pileMemberRelationService.selectPileMemberRelationByPileSn(dto.getPileSn());
if (CollectionUtils.isEmpty(relationList)) {
// 充电桩没有绑定任何人
}
List<String> adminList = relationList.stream()
.filter(x -> x.getType().equals("1"))
.map(PileMemberRelation::getMemberId)
.collect(Collectors.toList());
if (CollectionUtils.isEmpty(adminList)) {
// 没有管理员
}
// 校验身份
if (!adminList.contains(dto.getMemberId())) {
// 如果为空,说明此用户身份有误,不是管理员,抛出异常
throw new BusinessException(ReturnCodeEnum.CODE_AUTHENTICATION_ERROR);
}
List<String> userList = relationList.stream()
.filter(x -> !x.getType().equals("1"))
.map(PileMemberRelation::getMemberId)
.collect(Collectors.toList());
// 通过前端传的手机号查询是否有此用户
MemberBasicInfo memberBasicInfo = memberBasicInfoService.selectInfoByMobileNumber(dto.getPhoneNumber());
if (memberBasicInfo == null) {
// 为空说明此用户未注册平台账号
throw new BusinessException(ReturnCodeEnum.CODE_USER_IS_NOT_REGISTER);
}
if (userList.contains(memberBasicInfo.getMemberId())) {
// 不为空说明已绑定
throw new BusinessException(ReturnCodeEnum.CODE_USER_HAS_BEEN_THIS_PILE);
} else {
// 进行绑定,此用户为普通用户
PileMemberRelation info = new PileMemberRelation();
info.setPileSn(dto.getPileSn());
info.setMemberId(memberBasicInfo.getMemberId());
info.setType("2");
pileMemberRelationService.insertPileMemberRelation(info);
}
}
/**
* 获取枪口实时数据
* @param dto
* @return
*/
public PersonPileRealTimeVO getConnectorRealTimeInfo(QueryPersonPileDTO dto) {
// 根据memberId查出该用户 正在充电、个人桩启动(白名单支付方式)的订单号
OrderBasicInfo orderBasicInfo = OrderBasicInfo.builder()
.memberId(dto.getMemberId())
.orderStatus(OrderStatusEnum.IN_THE_CHARGING.getValue())
.pileConnectorCode(dto.getPileConnectorCode())
.startMode("3") // 3- 白名单支付
.build();
OrderBasicInfo basicInfo = orderBasicInfoService.getOrderBasicInfo(orderBasicInfo);
if (basicInfo == null){
throw new BusinessException(ReturnCodeEnum.CODE_NO_CHARGING_ORDER_ERROR);
}
String orderCode = basicInfo.getOrderCode();
// 根据订单号从redis中获取实时数据信息(默认时间倒叙排列,所以取第一条)
List<RealTimeMonitorData> chargingRealTimeData = orderBasicInfoService.getChargingRealTimeData(orderCode);
if (CollectionUtils.isEmpty(chargingRealTimeData)) {
throw new BusinessException(ReturnCodeEnum.CODE_NO_REAL_TIME_INFO);
}
RealTimeMonitorData realTimeMonitorData = chargingRealTimeData.get(0);
// 将需要的数据set
PersonPileRealTimeVO vo = PersonPileRealTimeVO.builder()
.chargingDegree(realTimeMonitorData.getChargingDegree())
.chargingTime(realTimeMonitorData.getSumChargingTime())
.startTime(DateUtils.formatDateTime(orderBasicInfo.getChargeStartTime()))
.instantCurrent(realTimeMonitorData.getOutputCurrent())
.instantVoltage(realTimeMonitorData.getOutputVoltage())
.instantPower(realTimeMonitorData.getOutputPower())
.build();
return vo;
}
/**
* 获取某枪口某段时间内累计信息
* @param dto
* @return
*/
public PersonPileConnectorSumInfoVO getAccumulativeInfo(QueryPersonPileDTO dto) {
List<PersonPileConnectorSumInfoVO> accumulativeInfo = orderBasicInfoService.getAccumulativeInfo(dto);
if (CollectionUtils.isEmpty(accumulativeInfo)) {
throw new BusinessException("00400011", "未查到相关订单信息!");
}
// BigDecimal sumChargingTime = BigDecimal.ZERO;
// BigDecimal sumUsedElectricity = BigDecimal.ZERO;
// // 将返回的结果进行for循环将总充电量、总充电时长进行累加充电时长需要通过 充电开始时间 和 充电结束时间 进行计算)
// for (PersonPileConnectorSumInfoVO personPileConnectorSumInfoVO : accumulativeInfo) {
// if (StringUtils.isNotBlank(personPileConnectorSumInfoVO.getChargeStartTime()) && StringUtils.isNotBlank(personPileConnectorSumInfoVO.getChargeEndTime())){
// long longChargingTime = DateUtils.intervalTime(personPileConnectorSumInfoVO.getChargeStartTime(), personPileConnectorSumInfoVO.getChargeEndTime());
// BigDecimal chargingTime = new BigDecimal(String.valueOf(longChargingTime));
// sumChargingTime = sumChargingTime.add(chargingTime);
// }
// BigDecimal chargingDegree = StringUtils.isBlank(personPileConnectorSumInfoVO.getSumChargingDegree())
// ? BigDecimal.ZERO
// : new BigDecimal(personPileConnectorSumInfoVO.getSumChargingDegree());
// sumUsedElectricity = sumUsedElectricity.add(chargingDegree);
// }
Map<String, String> sumInfo = getSumInfo(accumulativeInfo);
// set 对象
PersonPileConnectorSumInfoVO vo = new PersonPileConnectorSumInfoVO();
vo.setStartTime(dto.getStartTime());
vo.setEndTime(dto.getEndTime());
vo.setMemberId(dto.getMemberId());
vo.setSumChargingDegree(sumInfo.get("sumUsedElectricity"));
vo.setSumChargingTime(sumInfo.get("sumChargingTime"));
return vo;
}
/**
* 获取充电记录默认30天
*
* @param dto
*/
public PageResponse getChargingRecord(QueryPersonPileDTO dto) {
int pageNum = dto.getPageNum() == 0 ? 1 : dto.getPageNum();
int pageSize = dto.getPageSize() == 0 ? 10 : dto.getPageSize();
// 获取三十天前的数据
Date date = DateUtils.addMonths(new Date(), -1);
String dateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, date);
dto.setStartTime(dateStr);
dto.setEndTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()));
// 分页查询
PageHelper.startPage(pageNum, pageSize);
List<PersonPileConnectorSumInfoVO> accumulativeInfo = orderBasicInfoService.getAccumulativeInfo(dto);
if (CollectionUtils.isEmpty(accumulativeInfo)) {
throw new BusinessException("00400011", "未查到相关订单信息!");
}
PageInfo<PersonPileConnectorSumInfoVO> pageInfo = new PageInfo<>(accumulativeInfo);
for (PersonPileConnectorSumInfoVO personPileConnectorSumInfoVO : pageInfo.getList()) {
if (StringUtils.isNotBlank(personPileConnectorSumInfoVO.getChargeStartTime()) && StringUtils.isNotBlank(personPileConnectorSumInfoVO.getChargeEndTime())){
String datePoor = DateUtils.getDatePoor(DateUtils.parseDate(personPileConnectorSumInfoVO.getChargeEndTime()),
DateUtils.parseDate(personPileConnectorSumInfoVO.getChargeStartTime()));
personPileConnectorSumInfoVO.setSumChargingTime(datePoor);
}
}
return PageResponse.builder()
.pageNum(pageInfo.getPageNum())
.pageSize(pageInfo.getPageSize())
.list(pageInfo.getList())
.pages(pageInfo.getPages())
.total(pageInfo.getTotal())
.build();
}
/**
* 获取总充电时长、总充电量
*
* @param accumulativeInfo
* @return
*/
private Map<String, String> getSumInfo(List<PersonPileConnectorSumInfoVO> accumulativeInfo){
Map<String, String> resultMap = new HashMap<>();
BigDecimal sumChargingTime = BigDecimal.ZERO;
BigDecimal sumUsedElectricity = BigDecimal.ZERO;
// 将返回的结果进行for循环将总充电量、总充电时长进行累加充电时长需要通过 充电开始时间 和 充电结束时间 进行计算)
for (PersonPileConnectorSumInfoVO personPileConnectorSumInfoVO : accumulativeInfo) {
if (StringUtils.isNotBlank(personPileConnectorSumInfoVO.getChargeStartTime()) && StringUtils.isNotBlank(personPileConnectorSumInfoVO.getChargeEndTime())){
long longChargingTime = DateUtils.intervalTime(personPileConnectorSumInfoVO.getChargeStartTime(), personPileConnectorSumInfoVO.getChargeEndTime());
BigDecimal chargingTime = new BigDecimal(String.valueOf(longChargingTime));
sumChargingTime = sumChargingTime.add(chargingTime);
}
BigDecimal chargingDegree = StringUtils.isBlank(personPileConnectorSumInfoVO.getSumChargingDegree())
? BigDecimal.ZERO
: new BigDecimal(personPileConnectorSumInfoVO.getSumChargingDegree());
sumUsedElectricity = sumUsedElectricity.add(chargingDegree);
}
resultMap.put("sumChargingTime", String.valueOf(sumChargingTime));
resultMap.put("sumUsedElectricity", String.valueOf(sumUsedElectricity));
return resultMap;
}
}