Controller
/** * 领取优惠券 * @param couponId * @return */ @ApiOperation("领取优惠券") @GetMapping("/add/promotion/{coupon_id}") public JsonData addPromotionCoupon(@ApiParam(value = "优惠券id",required = true) @PathVariable("coupon_id")long couponId){ JsonData jsonData = couponService.addCoupon(couponId, CouponCategoryEnum.PROMOTION); return jsonData; }
Service
/** * 领取优惠券接口 * @param couponId * @param category * @return */ JsonData addCoupon(long couponId, CouponCategoryEnum category);
Impl
/** * 领劵接口 * 1、获取优惠券是否存在 * 2、校验优惠券是否可以领取:时间、库存、超过限制 * 3、扣减库存 * 4、保存领劵记录 * * 始终要记得,羊毛党思维很厉害,社会工程学 应用的很厉害 * * @param couponId * @param category * @return */ @Override public JsonData addCoupon(long couponId, CouponCategoryEnum category) { LoginUser loginUser = LoginInterceptor.threadLocal.get(); CouponDO couponDO = couponMapper.selectOne(new QueryWrapper<CouponDO>() .eq("id",couponId) .eq("category",category.name())); //优惠券是否可以领取 this.checkCoupon(couponDO,loginUser.getId()); //构建领劵记录 CouponRecordDO couponRecordDO = new CouponRecordDO(); BeanUtils.copyProperties(couponDO,couponRecordDO); couponRecordDO.setCreateTime(new Date()); couponRecordDO.setUseState(CouponStateEnum.NEW.name()); couponRecordDO.setUserId(loginUser.getId()); couponRecordDO.setUserName(loginUser.getName()); couponRecordDO.setCouponId(couponId); couponRecordDO.setId(null); //扣减库存 TODO int rows = 1; //couponMapper.reduceStock(couponId); if(rows==1){ //库存扣减成功才保存记录 couponRecordMapper.insert(couponRecordDO); }else { log.warn("发放优惠券失败:{},用户:{}",couponDO,loginUser); throw new BizException(BizCodeEnum.COUPON_NO_STOCK); } return JsonData.buildSuccess(); } /** * 校验是否可以领取 * @param couponDO * @param userId */ private void checkCoupon(CouponDO couponDO, Long userId) { if(couponDO==null){ throw new BizException(BizCodeEnum.COUPON_NO_EXITS); } //库存是否足够 if(couponDO.getStock()<=0){ throw new BizException(BizCodeEnum.COUPON_NO_STOCK); } //判断是否是否发布状态 if(!couponDO.getPublish().equals(CouponPublishEnum.PUBLISH.name())){ throw new BizException(BizCodeEnum.COUPON_GET_FAIL); } //是否在领取时间范围 long time = CommonUtil.getCurrentTimestamp(); long start = couponDO.getStartTime().getTime(); long end = couponDO.getEndTime().getTime(); if(time<start || time>end){ throw new BizException(BizCodeEnum.COUPON_OUT_OF_TIME); } //用户是否超过限制 int recordNum = couponRecordMapper.selectCount(new QueryWrapper<CouponRecordDO>() .eq("coupon_id",couponDO.getId()) .eq("user_id",userId)); if(recordNum >= couponDO.getUserLimit()){ throw new BizException(BizCodeEnum.COUPON_OUT_OF_LIMIT); } }
CouponStateEnum
public enum CouponStateEnum { /** * 新的可用 */ NEW, /** * 已经使用 */ USED, /** * 过期 */ EXPIRED }
本文作者为DBC,转载请注明。