| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385 |
- package com.cyksj.service.exchange.impl;
- import cn.hutool.core.date.DateField;
- import cn.hutool.core.date.DateTime;
- import cn.hutool.core.date.DateUtil;
- import cn.hutool.core.util.StrUtil;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.cyksj.common.annotation.NoSubmit;
- import com.cyksj.common.constant.Constant;
- import com.cyksj.common.exception.BusinessRuntimeException;
- import com.cyksj.common.snowflake.Sequence;
- import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
- import com.cyksj.common.util.StringUtil;
- import com.cyksj.dto.RedisKey;
- import com.cyksj.dto.Result;
- import com.cyksj.enums.GatewayResponse;
- import com.cyksj.mapper.*;
- import com.cyksj.mapper.manage.exchange.ExchangeCodeMapper;
- import com.cyksj.mapper.market.draw.LuckyDrawRecordMapper;
- import com.cyksj.model.entity.*;
- import com.cyksj.model.excel.ExcelExchangeCodeData;
- import com.cyksj.model.manage.views.AccountView;
- import com.cyksj.model.request.ExchangeCodeReq;
- import com.cyksj.model.request.ExchangeCodeTicket;
- import com.cyksj.redis.RedisService;
- import com.cyksj.service.exchange.ExchangeCodeService;
- import com.cyksj.service.relation.GroupRelationFrontService;
- import com.cyksj.service.template.TemplateCommonService;
- import com.ejlchina.searcher.BeanSearcher;
- import com.ejlchina.searcher.util.MapUtils;
- import lombok.RequiredArgsConstructor;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.BeanUtils;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import java.math.BigDecimal;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import java.util.Optional;
- /*
- *项目名: netflix
- *文件名: ExchangeCodeServiceImpl
- *创建者: JavaZou
- *创建时间:2022/11/7 15:41
- */
- @Service
- @RequiredArgsConstructor
- @Slf4j
- public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements ExchangeCodeService {
- private final GoodsDonMapper goodsDonMapper;
- private final GoodsDonSkuMapper goodsDonSkuMapper;
- private final ExchangeCodeMapper exchangeCodeMapper;
- private final GroupsRelationMapper groupsRelationMapper;
- private final GroupsMapper groupsMapper;
- private final RedisService redisService;
- private static final Sequence SEQUENCE = new Sequence(0);
- private final UserMapper userMapper;
- private final OrderDonMapper orderDonMapper;
- private static final GlobalThreadPoolTaskExecutor THREAD_POOL_TASK_EXECUTOR = GlobalThreadPoolTaskExecutor.getInstance();
- private final CustomerServiceMapper customerServiceMapper;
- private final LuckyDrawRecordMapper luckyDrawRecordMapper;
- private final TemplateCommonService templateCommonService;
- private final BeanSearcher beanSearcher;
- private final GroupRelationFrontService groupRelationFrontService;
- @Override
- @Transactional(rollbackFor = Throwable.class)
- public List<ExcelExchangeCodeData> createExchangeCode(ExchangeCodeReq exchangeCodeReq) {
- GoodsDon goodsDon = goodsDonMapper.selectById(exchangeCodeReq.getGoodsId());
- if (goodsDon == null) {
- throw BusinessRuntimeException.getInstance("所选平台已被删除");
- }
- if (Constant.realGoodsType.contains(goodsDon.getType())) {
- throw BusinessRuntimeException.getInstance("该类商品不支持生成兑换码");
- }
- GoodsDonSku goodsDonSku = goodsDonSkuMapper.selectById(exchangeCodeReq.getSkuId());
- if (goodsDonSku == null) {
- throw BusinessRuntimeException.getInstance("所选规格已被删除");
- }
- if (!goodsDonSku.getGoodsId().equals(exchangeCodeReq.getGoodsId())) {
- throw BusinessRuntimeException.getInstance("规格与平台不匹配");
- }
- List<ExcelExchangeCodeData> data = new ArrayList<>(exchangeCodeReq.getNumber());
- for (int i = 0; i < exchangeCodeReq.getNumber(); i++) {
- StringBuilder sb = new StringBuilder(32);
- sb.append(goodsDon.getSecondType() == 1 ? "YQ" : "FY");
- sb.append(getFillByGoodsId(exchangeCodeReq.getGoodsId()));
- sb.append(getFillByMonth(exchangeCodeReq.getSkuId()));
- //随即补充12位随即数,组成20位兑换码
- StringUtil.getRandomStr(sb, 12);
- ExchangeCode exchangeCode = new ExchangeCode();
- exchangeCode.setGoodsId(exchangeCodeReq.getGoodsId());
- exchangeCode.setSkuId(exchangeCodeReq.getSkuId());
- exchangeCode.setCode(sb.toString());
- exchangeCode.setUseStatus(false);
- exchangeCode.setType(exchangeCodeReq.getType());
- exchangeCodeMapper.insert(exchangeCode);
- ExcelExchangeCodeData excelExchangeCodeData = new ExcelExchangeCodeData();
- BeanUtils.copyProperties(exchangeCode, excelExchangeCodeData);
- excelExchangeCodeData.setTitle(goodsDon.getTitle());
- String specVal = goodsDonSku.getSpecVal();
- BigDecimal price = goodsDonSku.getPrice();
- excelExchangeCodeData.setSpecVal(String.format("%s%s", specVal, price.divide(BigDecimal.valueOf(100))));
- excelExchangeCodeData.setUseStatusStr(exchangeCode.getUseStatus() ? "已使用" : "未使用");
- data.add(excelExchangeCodeData);
- }
- return data;
- }
- @Override
- @Transactional(rollbackFor = Throwable.class)
- @NoSubmit
- public Result<String> getTicketByExchangeCode(ExchangeCodeTicket exchangeCodeTicket, Long userId) {
- if (StrUtil.isEmpty(exchangeCodeTicket.getCode())) {
- throw BusinessRuntimeException.getInstance("兑换码有误,请使用正确的兑换码");
- }
- ExchangeCode exchangeCode = this.getOne(Wrappers.lambdaQuery(ExchangeCode.class).eq(ExchangeCode::getCode, exchangeCodeTicket.getCode()).last("limit 1"));
- if (exchangeCode == null) {
- throw BusinessRuntimeException.getInstance("兑换码有误,请使用正确的兑换码");
- }
- if (exchangeCode.getUseStatus()) {
- throw BusinessRuntimeException.getInstance("该兑换码已使用");
- }
- //兑换成功
- exchangeCode.setUseStatus(true);
- exchangeCode.setUserId(userId);
- exchangeCode.setUseTime(DateTime.now());
- int update = exchangeCodeMapper.update(exchangeCode, Wrappers.lambdaQuery(ExchangeCode.class).eq(ExchangeCode::getId, exchangeCode.getId()).eq(ExchangeCode::getUseStatus, false));
- if (update != 1) {
- throw BusinessRuntimeException.getInstance("该兑换码已使用");
- }
- //是否是推广用户未登录订单关联的兑换码
- OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
- .eq(OrderDon::getIsNoLogin, true)
- .eq(OrderDon::getExCode, exchangeCode.getCode())
- .notIn(OrderDon::getStatus, Constant.noOrderStatus)
- .last("limit 1"));
- if (orderDon != null && orderDon.getStatus() == OrderDon.Status.refund) {
- throw BusinessRuntimeException.getInstance("您的订单已退款,无法使用该兑换码");
- }
- //生成车票订单
- getGroupTripsTicket(goodsDonSkuMapper.selectById(exchangeCode.getSkuId()), userId, orderDon, OrderDon.Type.EX_CODE);
- log.info("用户:{}通过兑换码:{}兑换成功", userId, exchangeCodeTicket.getCode());
- if (exchangeCode.getType() == 1) {
- luckyDrawRecordMapper.updateExCodeStatus(userId, exchangeCode.getCode());
- }
- return GatewayResponse.SUCCESS.newBuilder().toResult("兑换成功");
- }
- @Override
- public String getExCode(Long goodsId, Long skuId, Integer type) {
- ExchangeCodeReq exchangeCodeReq = new ExchangeCodeReq();
- exchangeCodeReq.setNumber(1);
- exchangeCodeReq.setGoodsId(goodsId);
- exchangeCodeReq.setSkuId(skuId);
- if (type != null) {
- exchangeCodeReq.setType(type);
- }
- try {
- List<ExcelExchangeCodeData> exchangeCodes = this.createExchangeCode(exchangeCodeReq);
- return exchangeCodes.get(0).getCode();
- } catch (Exception e) {
- return null;
- }
- }
- /**
- * 根据平台id获取填充的字符串
- */
- private String getFillByGoodsId(Long goodsId) {
- String goodsIdStr = String.valueOf(goodsId);
- if (goodsIdStr.length() == 1) {
- return String.format("%s%s%s", 0, 0, goodsId);
- }
- if (goodsIdStr.length() == 2) {
- return String.format("%s%s", 0, goodsId);
- }
- //最大不超过999
- if (goodsIdStr.length() > 3) {
- return goodsIdStr.substring(0, 3);
- }
- return goodsIdStr;
- }
- /**
- * 根据月份长度获取填充的字符串
- */
- private String getFillByMonth(Long skuMonth) {
- String goodsIdStr = String.valueOf(skuMonth);
- if (goodsIdStr.length() == 1) {
- return String.format("%s%s%s", 0, 0, skuMonth);
- }
- return String.format("%s%s", 0, skuMonth);
- }
- /**
- * 获取车位
- */
- @Override
- public GroupsRelation getGroupTripsTicket(GoodsDonSku sku, Long userId, OrderDon exCodeOrderDon, OrderDon.Type orderDonTye) {
- if (sku == null) {
- throw BusinessRuntimeException.getInstance("规格不存在,请联系客服");
- }
- GoodsDon goodsDon = goodsDonMapper.selectById(sku.getGoodsId());
- if (goodsDon == null) {
- throw BusinessRuntimeException.getInstance("平台不存在,请联系客服");
- }
- User user = userMapper.selectById(userId);
- if (user == null) {
- throw BusinessRuntimeException.getInstance("用户不存在");
- }
- GroupsRelation relation = null;
- //寻找差不多过期时间规格的车位
- relation = groupRelationFrontService.getSimilarExpiredGroupRelation(sku.getId(), sku.getMonths());
- if (relation == null) {
- GroupsTrips groups = groupsMapper.selectOne(Wrappers.lambdaQuery(GroupsTrips.class).eq(GroupsTrips::getSkuId, sku.getId()).gt(GroupsTrips::getAvailableNum, 0).last("limit 1").orderByAsc(GroupsTrips::getAvailableNum));
- if (groups == null) {
- //新增车位 并关联
- relation = createNewGroupTripsAndRelation(sku, groups, relation);
- } else {
- //寻找快满编车队进行占座
- relation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class)
- .eq(GroupsRelation::getGroupsId, groups.getId())
- .eq(GroupsRelation::getStatus, "none")
- .eq(GroupsRelation::getUserId, 0)
- .orderByAsc(GroupsRelation::getNum)
- .last("limit 1")
- );
- //如果占位失败 新增车位并关联
- if (relation == null) {
- relation = createNewGroupTripsAndRelation(sku, groups, relation);
- }
- }
- }
- try {
- //锁定座位
- setRelation(relation.getId(), userId);
- } catch (Exception e) {
- //失败重新给他分配车位
- getGroupTripsTicket(sku, userId, exCodeOrderDon, orderDonTye);
- redisService.del(RedisKey.GROUPS_RELATION_NUM_KEY + relation.getId());
- }
- relation.setUserId(userId);
- relation.setStatus(GroupsRelation.Status.validity);
- //如果续费增加时间,如果首次则设置当前时间为初始时间
- Date expiryTime = Optional.ofNullable(relation.getExpiryTime()).orElse(new Date());
- Date newDate = DateUtil.offset(expiryTime, DateField.MONTH, sku.getMonths() * 1);
- relation.setExpiryTime(newDate);
- relation.setStartTime(relation.getStartTime() == null ? new Date() : null);
- groupsRelationMapper.updateById(relation);
- Long relationId = relation.getId();
- OrderDon orderDon;
- if (exCodeOrderDon != null) {
- orderDon = exCodeOrderDon;
- orderDon.setRelationId(relationId);
- orderDon.setUserId(userId);
- orderDon.setStatus(goodsDon.getType() == 1 && goodsDon.getSecondType() == 2 ? OrderDon.Status.complete : OrderDon.Status.hasPayment);
- orderDonMapper.updateById(orderDon);
- } else {
- /* 生成订单 */
- String donNo = SEQUENCE.nextId().toString();
- orderDon = new OrderDon();
- orderDon.setOrderNo(donNo);
- orderDon.setOpenId(user.getOpenId());
- orderDon.setMoney(BigDecimal.ZERO);
- orderDon.setSkuId(sku.getId());
- orderDon.setRelationId(relationId);
- //默认数量为1
- orderDon.setNum(1);
- orderDon.setGoodsId(sku.getGoodsId());
- orderDon.setStatus(goodsDon.getType() == 1 && goodsDon.getSecondType() == 2 ? OrderDon.Status.complete : OrderDon.Status.hasPayment);
- //兑换码兑换
- orderDon.setType(orderDonTye);
- orderDon.setUserId(user.getId());
- orderDonMapper.insert(orderDon);
- }
- if (StrUtil.isNotEmpty(user.getOpenId())) {
- //发送模板消息
- THREAD_POOL_TASK_EXECUTOR.execute(() -> {
- try {
- if (StrUtil.isNotEmpty(user.getOpenId())) {
- log.info("用户{}兑换车位成功,发送新订单模板消息", user.getId());
- templateCommonService.newOderSendMsgByType(orderDon, goodsDon, sku, user, user.getOpenId());
- }
- } catch (Exception e) {
- log.info("用户{}兑换车位成功,发送消息失败:{}", user.getId(), e);
- }
- });
- }
- THREAD_POOL_TASK_EXECUTOR.execute(() -> {
- try {
- //发送至客服消息
- List<CustomerService> customerServices = customerServiceMapper.selectList(null);
- for (CustomerService customerService : customerServices) {
- log.info("向客服{}发送用户兑换码兑换车票消息通知..", customerService.getNickName());
- templateCommonService.newOderSendMsgByType(orderDon, goodsDon, sku, user, customerService.getOpenId());
- }
- } catch (Exception e) {
- log.error("向客服发送用户{}兑换码兑换车票成功,发送消息失败:{}", user.getId(), e);
- }
- });
- relation.setOrderId(orderDon.getId());
- return relation;
- }
- private void setRelation(Long relationId, Long userId) {
- if (redisService.get(RedisKey.GROUPS_RELATION_NUM_KEY + relationId) != null) {
- throw new BusinessRuntimeException("客官手慢啦,该座位已经有人啦!");
- } else {
- redisService.set(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L);
- GroupsRelation relation = groupsRelationMapper.selectById(relationId);
- int count = groupsMapper.decrAvailableNum(relation.getGroupsId());
- if (count == 0) {
- log.error("车位异常 groupId:{}", relation.getGroupsId());
- throw new BusinessRuntimeException("车位异常");
- }
- }
- }
- /**
- * 新增新车位并关联车位
- */
- private GroupsRelation createNewGroupTripsAndRelation(GoodsDonSku sku, GroupsTrips groups, GroupsRelation relation) {
- //通过兑换码兑换车票 新增车位
- if (groups == null) {
- groups = new GroupsTrips();
- }
- //补充占位
- if (relation == null) {
- relation = new GroupsRelation();
- }
- groups.setSkuId(sku.getId());
- groups.setNum(sku.getNum());
- groups.setAvailableNum(sku.getNum());
- if (sku.getGoodsId() == 23) {
- AccountView accountView = beanSearcher.searchFirst(AccountView.class, MapUtils.builder().field(AccountView::getGoodsId, 23).onlySelect(AccountView::getId).build());
- if (accountView != null) {
- groups.setAccountId(accountView.getId());
- groups.setStatus(GroupsTrips.Status.validity);
- groups.setRemark("已设置唯一账号");
- }else {
- groups.setStatus(GroupsTrips.Status.waiting);
- groups.setRemark("等待设置账号");
- }
- } else {
- groups.setStatus(GroupsTrips.Status.waiting);
- groups.setRemark("等待设置账号");
- }
- groupsMapper.insert(groups);
- relation.setGroupsId(groups.getId());
- relation.setNum(1);
- relation.setStatus(GroupsRelation.Status.locking);
- relation.setGroupsId(groups.getId());
- groupsRelationMapper.insert(relation);
- //补充其他占位
- for (int i = 2; i <= groups.getNum(); i++) {
- GroupsRelation groupsRelation = new GroupsRelation();
- groupsRelation.setGroupsId(groups.getId());
- groupsRelation.setNum(i);
- groupsRelation.setStatus(GroupsRelation.Status.none);
- groupsRelationMapper.insert(groupsRelation);
- }
- return relation;
- }
- }
|