Commit f04684c8 by 吕明尚

Merge branch 'dev' into dev-lms

# Conflicts:
#	share-system/src/main/java/share/system/service/impl/OrderPayServiceImpl.java
#	share-system/src/main/java/share/system/service/impl/OrderRefundServiceImpl.java
parents bc308363 2ea0069a
......@@ -7,7 +7,10 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
......@@ -17,7 +20,9 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import share.common.constant.CacheConstants;
import share.common.constant.MqttConstants;
import share.common.core.domain.AjaxResult;
import share.common.core.redis.RedisUtil;
import share.common.utils.StringUtils;
import share.system.domain.SysCache;
......@@ -32,6 +37,8 @@ public class CacheController
{
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Autowired
private RedisUtil redisUtil;
private final static List<SysCache> caches = new ArrayList<SysCache>();
{
......@@ -42,6 +49,8 @@ public class CacheController
caches.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交"));
caches.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理"));
caches.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数"));
caches.add(new SysCache(MqttConstants.MQTT_REDIS_KEY, "设备下发消息队列"));
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
......@@ -87,7 +96,13 @@ public class CacheController
@GetMapping("/getValue/{cacheName}/{cacheKey}")
public AjaxResult getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey)
{
String cacheValue = redisTemplate.opsForValue().get(cacheKey);
String cacheValue = "";
if (MqttConstants.MQTT_REDIS_KEY.equals(cacheName)) {
List<Object> list = redisUtil.lRange(cacheKey, 0, -1);
cacheValue = JSONUtil.toJsonStr(list);
} else {
cacheValue = redisTemplate.opsForValue().get(cacheKey);
}
SysCache sysCache = new SysCache(cacheName, cacheKey, cacheValue);
return AjaxResult.success(sysCache);
}
......
......@@ -2,6 +2,8 @@ package share.web.controller.system;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import cn.hutool.core.util.StrUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
......@@ -15,6 +17,7 @@ import org.springframework.web.bind.annotation.RestController;
import share.common.annotation.Log;
import share.common.core.controller.BaseController;
import share.common.core.domain.AjaxResult;
import share.common.core.domain.entity.SysUser;
import share.common.enums.BusinessType;
import share.common.utils.SecurityUtils;
import share.system.domain.DeviceDto;
......@@ -22,11 +25,9 @@ import share.system.mqtt.MqttGatewayComponent;
import share.system.domain.Device;
import share.system.domain.vo.DeviceParamVo;
import share.system.domain.vo.MqttxVo;
import share.system.service.DeviceLogService;
import share.system.service.DeviceService;
import share.system.service.*;
import share.common.utils.poi.ExcelUtil;
import share.common.core.page.TableDataInfo;
import share.system.service.MqttxService;
/**
* 设备信息Controller
......@@ -41,11 +42,9 @@ public class DeviceController extends BaseController
@Autowired
private DeviceService deviceService;
@Autowired
private MqttxService mqttxService;
@Autowired
private DeviceLogService deviceLogService;
private DeviceOpService deviceOpService;
@Autowired
private MqttGatewayComponent mqttGatewayComponent;
private ISysUserService sysUserService;
/**
* 查询设备信息列表
......@@ -123,14 +122,13 @@ public class DeviceController extends BaseController
@PostMapping(value = "/openOrClose")
public AjaxResult openOrClose(@RequestBody DeviceParamVo deviceParam)
{
// 获取mqtt的topic、payload
MqttxVo mqttxVo = mqttxService.openOrCloseDevice(deviceParam.getDevId(),
SecurityUtils.getUsername(), deviceParam.getOpType());
// 发送mqtt消息
mqttGatewayComponent.sendToMqtt(mqttxVo.getTopic(), 0, mqttxVo.getPayload());
// 写日志记录
int result = deviceLogService.addDeviceLog(mqttxVo, SecurityUtils.getUsername());
return toAjax(result);
Long userId = SecurityUtils.getUserId();
if (userId != null) {
SysUser sysUser = sysUserService.selectUserById(userId);
deviceParam.setPhone(sysUser.getPhonenumber());
deviceOpService.openOrCloseDev(deviceParam);
}
return toAjax(true);
}
/**
......
......@@ -14,6 +14,7 @@ import share.common.core.controller.BaseController;
import share.common.core.domain.AjaxResult;
import share.common.enums.BusinessType;
import share.system.domain.SOrder;
import share.system.domain.vo.SOrderDto;
import share.system.request.OrderRefundRequest;
import share.system.service.ISOrderService;
import share.common.utils.poi.ExcelUtil;
......@@ -121,4 +122,14 @@ public class SOrderController extends BaseController
public AjaxResult<Boolean> refund(@Validated OrderRefundRequest request) {
return toAjax(sOrderService.refundAudit(request));
}
/**
* 人工修改订单
*/
// @PreAuthorize("hasAuthority('system:order:modify')")
@PutMapping(value = "/modify")
public AjaxResult<Boolean> modifyOrder(@RequestBody SOrderDto sOrderDto) {
return toAjax(sOrderService.modifyOrder(sOrderDto));
}
}
......@@ -22,6 +22,7 @@ wechat:
signKey: ZEKu56XCezuESfNEdM4zVZEN3cz2PuHz
certPath: /var/gxpt/wechat_ssl/apiclient_cert.p12
token: coujio
miniprogram_state: formal
wx:
miniapp:
configs:
......@@ -219,3 +220,5 @@ order:
mqtt:
device-op-last-time: -5
device-gateway-last-report-time: -10
api:
domain: https://www.coujio.com
\ No newline at end of file
......@@ -10,6 +10,21 @@ package share.common.constant;
public class MqttConstants {
/**
* 设备消息发送redis缓存前缀
*/
public static final String MQTT_REDIS_KEY = "MQTT_REDIS_KEY:";
/**
* 记录最后设备消息发送时间redis
*/
public static final String MQTT_DEVICE_LAST_TIME_KEY = "MQTT_DEVICE_LAST_TIME_KEY:";
/**
* 记录最后每个门店设备消息发送最后时间redis
*/
public static final String MQTT_STORE_LAST_TIME_KEY = "MQTT_STORE_LAST_TIME_KEY:";
/**
* 动作: 请求端为req
*/
public static final String MQTT_AC_REQ = "req";
......
......@@ -224,6 +224,7 @@ public class WeChatConstants {
// 微信部分
// --------------------------------------------------------------------------------------------------------
public static final int WECHAT_TOKEN_EXPIRED_CODE = 40001;
/** 获取accessToken的url */
public static final String WECHAT_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}";
/** 开放平台获取accessToken的url */
......
......@@ -227,6 +227,18 @@ public class RedisUtil {
}
/**
* 列表添加右边添加
* @param k string key
* @param v Object v
* @author Mr.Zhang
* @since 2020-04-13
*/
public void rPush(String k, Object v) {
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k, v);
}
/**
* 从右边拿出来一个
* @param k string key
* @param t Long 超时秒数
......@@ -236,6 +248,28 @@ public class RedisUtil {
}
/**
* 某一个信息获取
* @param k string key
* @param l long l
* @return List<Object>
*/
public Object getIndex(String k, long l) {
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.index(k, l);
}
/**
* 设置list中指定下标的值,采用干的是替换规则, 最左边的下标为0;-1表示最右边的一个
*
* @param k 主键
* @param index 下标
* @param v 值
*/
public void setListByIndex(String k, Integer index, Object v) {
redisTemplate.opsForList().set(k, index, v);
}
/**
* 列表获取数量
* @param k string key
* @return Long
......
......@@ -4,9 +4,11 @@ import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.date.LocalDateTimeUtil;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
......@@ -29,13 +31,16 @@ import java.util.Map;
**/
@RestController
@Slf4j
@AllArgsConstructor
@RequiredArgsConstructor
@RequestMapping("/weixinpublic")
public class WxMsgPushController {
private final WxMaService wxMaService;
private final WxMaProperties properties;
@Autowired
private WechatNewService wechatNewService;
@Value("${wechat.miniprogram_state}")
private String miniprogramState;
/**
* // * 跳转的小程序页面
* //
......@@ -73,7 +78,7 @@ public class WxMsgPushController {
HashMap<String, SendTemplateMessageItemVo> data = new HashMap<>();
TemplateMessageVo templateMessageVo = new TemplateMessageVo();
templateMessageVo.setTouser(openId);
templateMessageVo.setMiniprogram_state("trial");
templateMessageVo.setMiniprogram_state(miniprogramState);
templateMessageVo.setPage("/pages/orderResult/orderResult?orderNo=CJ431705545528576539");
templateMessageVo.setTemplate_id(MessageReminderEnum.END.getValue());
data.put("thing5", new SendTemplateMessageItemVo("武汉"));
......
......@@ -51,8 +51,6 @@ public class SOrderController extends BaseController
public TableDataInfo list(SOrder sOrder)
{
startPage();
SConsumer user = FrontTokenComponent.getWxSConsumerEntry();
sOrder.setConsumerId(user.getId());
List<SOrderVo> list = sOrderService.selectPayedSOrderVoList(sOrder);
return getDataTable(list);
}
......
......@@ -47,7 +47,6 @@ public class SRoomController extends BaseController {
@ApiOperation(value = "房间列表")
@GetMapping("/list")
public R<List<SRoomVo>> list(SRoom sRoom) {
startPage();
List<SRoomVo> list = sRoomService.selectSRoomVoList(sRoom);
return R.ok(list);
}
......
......@@ -22,6 +22,7 @@ wechat:
signKey: ZEKu56XCezuESfNEdM4zVZEN3cz2PuHz
certPath: /Users/project/pseer/apiclient_cert.p12
token: coujio
miniprogram_state: formal
wx:
miniapp:
configs:
......@@ -216,3 +217,5 @@ order:
mqtt:
device-op-last-time: -5
device-gateway-last-report-time: -10
api:
domain: https://www.coujio.com
......@@ -3,9 +3,11 @@ package share.quartz.task;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.Store;
import org.slf4j.Logger;
......@@ -248,6 +250,11 @@ public class OrderTask {
logger.info("订单号为:" + jsonObject.getStr("orderNo") + "的订单不存在");
return;
}
if (OrderStatusEnum.CANCEL.getCode().equals(byOrderNo.getStatus())) {
redisUtil.delete(o);
logger.info("订单号为:" + jsonObject.getStr("orderNo") + "的订单已取消");
return;
}
//时间到期前30分钟到29分
long expire = (expirationTime.getTime() - new Date().getTime()) / 1000;
if (expire < TEN_MINUTES && expire > NINE_MINUTES) {
......@@ -308,4 +315,49 @@ public class OrderTask {
}
}
/**
* 订单状态因未知原因导致时间结束未完成的,修改订单状态
* 房间状态因未知原因导致未有使用中订单而占用的,修改房间状态
*/
public void orderCompensate() {
// 订单状态处理
LambdaQueryWrapper<SOrder> queryWrapper = new LambdaQueryWrapper();
queryWrapper.le(SOrder::getEndDate, DateUtil.offset(DateUtil.date(), DateField.MINUTE, -5));
queryWrapper.in(SOrder::getStatus, OrderStatusEnum.UNUSED.getCode(),OrderStatusEnum.INUSE.getCode());
queryWrapper.eq(SOrder::getPayStatus, 1);
List<SOrder> orders = orderService.list(queryWrapper);
if (orders != null && orders.size() > 0) {
orders.forEach(order -> {
order.setStatus(OrderStatusEnum.USED.getCode());
order.setUpdateTime(new Date());
});
orderService.updateBatchById(orders,orders.size());
}
// 房间状态处理
LambdaQueryWrapper<SRoom> queryRoomWrapper = new LambdaQueryWrapper();
queryRoomWrapper.eq(SRoom::getStatus, RoomStatusEnum.HOLD.getValue());
List<SRoom> rooms = roomService.list(queryRoomWrapper);
if (rooms != null && rooms.size() > 0) {
List<Long> roomIds = rooms.stream().map(SRoom::getId).collect(Collectors.toList());
// 房间使用中订单
LambdaQueryWrapper<SOrder> queryOrderWrapper = new LambdaQueryWrapper();
queryOrderWrapper.eq(SOrder::getStatus, OrderStatusEnum.INUSE.getCode());
queryOrderWrapper.in(SOrder::getRoomId, roomIds);
queryOrderWrapper.eq(SOrder::getPayStatus, 1);
List<SOrder> orderList = orderService.list(queryOrderWrapper);
Map<Long,List<SOrder>> sOrderMap = Optional.ofNullable(orderList).orElse(new ArrayList<>()).stream().collect(Collectors.groupingBy(SOrder::getRoomId));
List<SRoom> roomList = new ArrayList<>();
rooms.forEach(room -> {
if (sOrderMap.get(room.getId()) == null || sOrderMap.get(room.getId()).size() == 0) {
room.setStatus(RoomStatusEnum.FREE.getValue());
room.setUpdateTime(new Date());
roomList.add(room);
}
});
if (roomList.size() > 0) {
roomService.updateBatchById(roomList, roomList.size());
}
}
}
}
package share.quartz.task;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
......@@ -23,10 +26,12 @@ import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import share.common.constant.MqttConstants;
import share.common.core.redis.RedisUtil;
import share.common.enums.*;
import share.common.exception.base.BaseException;
import share.system.domain.*;
import share.system.domain.vo.MqttxVo;
import share.system.mapper.SConsumerMapper;
import share.system.service.*;
import share.system.service.impl.SOrderServiceImpl;
......@@ -298,4 +303,42 @@ public class RedisTask {
DatePattern.NORM_DATETIME_PATTERN), "1", 10L);
}
/**
* 设备消息发送队列失败中断监控
* 删除中断消息,继续发送设备消息
*/
public void monitorDeviceQueue() {
Set<String> keys = redisTemplate.keys(MqttConstants.MQTT_STORE_LAST_TIME_KEY + "*");
if (keys.size() == 0) {
return;
}
Date nowDate = DateUtil.date();
keys.stream().forEach(key -> {
String value = redisUtil.get(key);
if (StrUtil.isNotEmpty(value)) {
JSONObject jsonObject = new JSONObject(value);
Date sendTime = jsonObject.getDate("sendTime");
Long storeId = jsonObject.getLong("storeId");
if (sendTime != null) {
long betweenDay = DateUtil.between(sendTime, nowDate, DateUnit.SECOND);
if (betweenDay > 15L) {
String key2 = StrUtil.concat(true, MqttConstants.MQTT_REDIS_KEY,
StrUtil.toString(storeId));
if (redisUtil.getListSize(key2) > 0) {
// 删除失败消息redis记录
redisUtil.getRightPop(key2, 10L);
// 获取当前需要发送的消息
Object data = redisUtil.getIndex(key2, -1);
if (null != data) {
MqttxVo vo = BeanUtil.toBean(data, MqttxVo.class);
// 发送新的消息
deviceOpService.sendMqtt(vo, storeId);
}
}
}
}
}
});
}
}
......@@ -57,6 +57,9 @@ public class DeviceLog extends BaseEntity
@Excel(name = "描述")
private String description;
@Excel(name = "重新发送次数")
private Integer afreshNum;
/**
* 房间名称
*/
......
......@@ -35,4 +35,19 @@ public class MqttxVo extends BaseEntity {
/** 消息描述:开门、开灯、网关设备绑定等 */
private String mqttDescribe;
/** 消息操作类型 */
private String opType;
/**
* 重新发送次数
*/
private Integer refreshNum;
/**
* 是否需要发送短信及结果:0-不需要,1-需要,2-发送成功,4-发送失败
*/
private Integer sendSmsResult;
private String phone;
}
package share.system.domain.vo;
import lombok.Data;
@Data
public class SOrderDto {
//订单滨海
private String orderNo;
//是否消劵
private Integer isReverseconsume;
//备注
private String remark;
}
......@@ -71,4 +71,7 @@ public interface DeviceLogMapper extends BaseMapper<DeviceLog>
*/
List<DeviceLog> selectListByMaxId(@Param("devIds") List<String> devIds, @Param("startDate") Date startDate);
DeviceLog selectDeviceLogOneBySeqMax(String seq);
int updateDeviceById(DeviceLog deviceLog);
}
......@@ -12,6 +12,12 @@ import share.system.domain.vo.MqttxVo;
public interface DeviceOpService {
/**
* 管理系统开门、通电、断电
* @param deviceParam
*/
void openOrCloseDev(DeviceParamVo deviceParam);
/**
* 小程序订单开门、通电
* @param deviceParam
*/
......@@ -98,4 +104,10 @@ public interface DeviceOpService {
*/
void deleteDevicePassword(Long roomId, String param, String phone, String opType);
/**
* mqtt 消息发送
* @param mqttxVo 消息内容
*/
void sendMqtt(MqttxVo mqttxVo, Long storeId);
}
......@@ -73,4 +73,12 @@ public interface DeviceService extends IService<Device>
List<Device> selectDeviceListByIds(List<Long> collect);
List<Device> selectDeviceByRoomId(Long roomId);
/**
* 查询设备信息
*
* @param devId 设备devId
* @return 设备信息
*/
Device selectDeviceByDevId(String devId);
}
......@@ -7,6 +7,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
import share.system.domain.SConsumerCoupon;
import share.system.domain.SOrder;
import share.system.domain.vo.OrderVo;
import share.system.domain.vo.SOrderDto;
import share.system.domain.vo.SOrderVo;
import share.system.request.CreateOrderRequest;
import share.system.request.OrderComputedPriceRequest;
......@@ -188,4 +189,5 @@ public interface ISOrderService extends IService<SOrder>
boolean isRefund(SOrder order, SConsumerCoupon coupon);
int modifyOrder(SOrderDto sOrderDto);
}
......@@ -151,6 +151,7 @@ public class DeviceLogServiceImpl extends ServiceImpl<DeviceLogMapper, DeviceLog
deviceLog.setMqttDescribe(mqttxVo.getMqttDescribe());
deviceLog.setCreateTime(DateUtils.getNowDate());
deviceLog.setCreateBy(userNmae);
deviceLog.setAfreshNum(mqttxVo.getRefreshNum());
return deviceLogMapper.insertDeviceLog(deviceLog);
}
}
package share.system.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import share.common.constant.Constants;
import share.common.constant.MqttConstants;
import share.common.core.redis.RedisUtil;
import share.common.enums.DeviceType;
import share.common.enums.OpTypeEnum;
import share.common.utils.SecurityUtils;
......@@ -44,6 +52,93 @@ public class DeviceOpServiceImpl implements DeviceOpService {
private DeviceLogService deviceLogService;
@Autowired
private DeviceMapper deviceMapper;
@Autowired
private RedisUtil redisUtil;
/**
* 设备消息redis缓存
* @param devId 设备id
* @param mqttxVo 消息内容
*/
private void setRedisCache(String devId, MqttxVo mqttxVo) {
// 设备信息
LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper();
queryWrapper.eq(Device::getDevId, devId);
Device device = deviceMapper.selectOne(queryWrapper);
// 房间信息
LambdaQueryWrapper<SRoom> queryRoomWrapper = new LambdaQueryWrapper();
queryRoomWrapper.eq(SRoom::getId, device.getRoomId());
SRoom room = roomMapper.selectOne(queryRoomWrapper);
if (room != null) {
String key = StrUtil.concat(true, MqttConstants.MQTT_REDIS_KEY,
StrUtil.toString(room.getStoreId()));
Long size = redisUtil.getListSize(key);
if (size > 0) {
// 如果存在数据
// 加入redis缓存队列
boolean isExist = Boolean.FALSE;
List<Object> list = redisUtil.lRange(key, 0, -1);
for (Object o : list) {
MqttxVo vo = BeanUtil.toBean(o, MqttxVo.class);
if (vo.getSeq().equals(mqttxVo.getSeq())) {
isExist = Boolean.TRUE;
}
}
if (!isExist) {
// 如果redis队列不存在此消息,添加队列
// 加入发送mqtt消息队列
mqttxVo.setRefreshNum(0);
mqttxVo.setSendSmsResult(0);
redisUtil.lPush(key, mqttxVo);
}
} else {
// 加入发送mqtt消息队列
mqttxVo.setRefreshNum(0);
mqttxVo.setSendSmsResult(0);
redisUtil.lPush(key, mqttxVo);
// 发送mqtt消息
this.sendMqtt(mqttxVo, room.getStoreId());
}
}
}
/**
* 设备操作消息发送(开门、通电、断电)
* @param mqttxVo
*/
@Override
public void sendMqtt(MqttxVo mqttxVo, Long storeId) {
// 发送mqtt消息
mqttGatewayComponent.sendToMqtt(mqttxVo.getTopic(), 0, mqttxVo.getPayload());
// 记录当前设备最后发送时间
redisUtil.set(MqttConstants.MQTT_DEVICE_LAST_TIME_KEY + mqttxVo.getDevId(), DateUtil.now());
// 记录当前门店最后发送设备时间
JSONObject jsonObject = new JSONObject();
jsonObject.set("storeId", storeId);
jsonObject.set("sendTime", DateUtil.date());
redisUtil.set(MqttConstants.MQTT_STORE_LAST_TIME_KEY + storeId, JSONUtil.toJsonStr(jsonObject));
// 写日志记录
deviceLogService.addDeviceLog(mqttxVo, mqttxVo.getPhone());
}
/**
* 管理系统开门、通电、断电
* @param deviceParam
*/
@Override
public void openOrCloseDev(DeviceParamVo deviceParam) {
Device device = deviceMapper.selectDeviceByDevId(deviceParam.getDevId());
if (device != null) {
if (DeviceType.DEVICE_CCEE.getCode().equals(device.getDevType())) {
// 门锁
this.deviceOpInit(device.getDevId(), deviceParam.getPhone(), deviceParam.getOpType(), true, 2L);
}
if (DeviceType.DEVICE_0001.getCode().equals(device.getDevType())) {
// 取电开关
this.deviceOpInit(device.getDevId(), deviceParam.getPhone(), deviceParam.getOpType(), true, 2L);
}
}
}
/**
* 小程序订单开门
......@@ -62,7 +157,7 @@ public class DeviceOpServiceImpl implements DeviceOpService {
}
if (DeviceType.DEVICE_0001.getCode().equals(device.getDevType())) {
// 取电开关
this.deviceOpInit(device.getDevId(), deviceParam.getPhone(), OpTypeEnum.GET_ELECTRIC.getCode(), true, 5L);
this.deviceOpInit(device.getDevId(), deviceParam.getPhone(), OpTypeEnum.GET_ELECTRIC.getCode(), true, 2L);
}
}
......@@ -87,7 +182,7 @@ public class DeviceOpServiceImpl implements DeviceOpService {
}
if (DeviceType.DEVICE_0001.getCode().equals(device.getDevType())) {
// 取电开关
this.deviceOpInit(device.getDevId(), phone, OpTypeEnum.GET_ELECTRIC.getCode(), true, 5L);
this.deviceOpInit(device.getDevId(), phone, OpTypeEnum.GET_ELECTRIC.getCode(), true, 2L);
}
}
......@@ -103,11 +198,9 @@ public class DeviceOpServiceImpl implements DeviceOpService {
Thread.sleep(m * 1000);
// 获取mqtt的topic、payload
MqttxVo mqttxVo = mqttxService.openOrCloseDevice(devId, phone, opType);
// 发送mqtt消息
mqttGatewayComponent.sendToMqtt(mqttxVo.getTopic(), 0, mqttxVo.getPayload());
// 写日志记录
deviceLogService.addDeviceLog(mqttxVo, phone);
logger.info("延时执行开门、取电操作完成!");
mqttxVo.setPhone(phone);
// 设置消息队列
this.setRedisCache(devId, mqttxVo);
} catch (InterruptedException e) {
e.printStackTrace();
}
......@@ -116,10 +209,9 @@ public class DeviceOpServiceImpl implements DeviceOpService {
} else {
// 获取mqtt的topic、payload
MqttxVo mqttxVo = mqttxService.openOrCloseDevice(devId, phone, opType);
// 发送mqtt消息
mqttGatewayComponent.sendToMqtt(mqttxVo.getTopic(), 0, mqttxVo.getPayload());
// 写日志记录
deviceLogService.addDeviceLog(mqttxVo, phone);
mqttxVo.setPhone(phone);
// 设置消息队列
this.setRedisCache(devId, mqttxVo);
}
}
......@@ -128,7 +220,6 @@ public class DeviceOpServiceImpl implements DeviceOpService {
* @param devId 网关设备dev_id
* @return
*/
@Override
public void clearGatewayDevice(String devId, String userName) {
// 获取mqtt的topic、payload
MqttxVo mqttxVo = mqttxService.clearGatewayDevice(devId);
......@@ -143,7 +234,7 @@ public class DeviceOpServiceImpl implements DeviceOpService {
* @param devId 网关设备dev_id
* @return
*/
@Override
public void addGatewayDevice(String devId, String userName) {
// 获取mqtt的topic、payload
MqttxVo mqttxVo = mqttxService.addGatewayDevice(devId);
......@@ -175,10 +266,9 @@ public class DeviceOpServiceImpl implements DeviceOpService {
for (Device device : list) {
// 获取mqtt的topic、payload
MqttxVo mqttxVo = mqttxService.actionExecute(device.getDevId(), phone, content, startTime, endTime, number);
// 发送mqtt消息
mqttGatewayComponent.sendToMqtt(mqttxVo.getTopic(), 0, mqttxVo.getPayload());
// 写日志记录
deviceLogService.addDeviceLog(mqttxVo, phone);
mqttxVo.setPhone(phone);
// 设置消息队列
this.setRedisCache(device.getDevId(), mqttxVo);
}
}
}
......@@ -211,10 +301,9 @@ public class DeviceOpServiceImpl implements DeviceOpService {
for (Device device : list) {
// 获取mqtt的topic、payload
MqttxVo mqttxVo = mqttxService.actionExecute(device.getDevId(), phone, content, startTime, endTime, number);
// 发送mqtt消息
mqttGatewayComponent.sendToMqtt(mqttxVo.getTopic(), 0, mqttxVo.getPayload());
// 写日志记录
deviceLogService.addDeviceLog(mqttxVo, phone);
mqttxVo.setPhone(phone);
// 设置消息队列
this.setRedisCache(device.getDevId(), mqttxVo);
}
logger.info("延时执行语音播报完成!");
} catch (InterruptedException e) {
......@@ -255,10 +344,9 @@ public class DeviceOpServiceImpl implements DeviceOpService {
Thread.sleep(m * 1000);
// 获取mqtt的topic、payload
MqttxVo mqttxVo = mqttxService.openOrCloseDevice(device.getDevId(), phone, opType);
// 发送mqtt消息
mqttGatewayComponent.sendToMqtt(mqttxVo.getTopic(), 0, mqttxVo.getPayload());
// 写日志记录
deviceLogService.addDeviceLog(mqttxVo, phone);
mqttxVo.setPhone(phone);
// 设置消息队列
this.setRedisCache(device.getDevId(), mqttxVo);
logger.info("延时执行开锁/关锁、取电/断电完成!");
} catch (InterruptedException e) {
e.printStackTrace();
......@@ -268,10 +356,9 @@ public class DeviceOpServiceImpl implements DeviceOpService {
} else {
// 获取mqtt的topic、payload
MqttxVo mqttxVo = mqttxService.openOrCloseDevice(device.getDevId(), phone, opType);
// 发送mqtt消息
mqttGatewayComponent.sendToMqtt(mqttxVo.getTopic(), 0, mqttxVo.getPayload());
// 写日志记录
deviceLogService.addDeviceLog(mqttxVo, phone);
mqttxVo.setPhone(phone);
// 设置消息队列
this.setRedisCache(device.getDevId(), mqttxVo);
}
});
}
......@@ -299,10 +386,9 @@ public class DeviceOpServiceImpl implements DeviceOpService {
list.stream().forEach(device -> {
// 获取mqtt的topic、payload
MqttxVo mqttxVo = mqttxService.setOpenPassword(device.getDevId(), param, startTime, endTime, phone, opType);
// 发送mqtt消息
mqttGatewayComponent.sendToMqtt(mqttxVo.getTopic(), 0, mqttxVo.getPayload());
// 写日志记录
deviceLogService.addDeviceLog(mqttxVo, phone);
mqttxVo.setPhone(phone);
// 设置消息队列
this.setRedisCache(device.getDevId(), mqttxVo);
});
}
}
......@@ -326,10 +412,9 @@ public class DeviceOpServiceImpl implements DeviceOpService {
list.stream().forEach(device -> {
// 获取mqtt的topic、payload
MqttxVo mqttxVo = mqttxService.deleteOpenPassword(device.getDevId(), param, null, null, phone, opType);
// 发送mqtt消息
mqttGatewayComponent.sendToMqtt(mqttxVo.getTopic(), 0, mqttxVo.getPayload());
// 写日志记录
deviceLogService.addDeviceLog(mqttxVo, phone);
mqttxVo.setPhone(phone);
// 设置消息队列
this.setRedisCache(device.getDevId(), mqttxVo);
});
}
}
......
......@@ -125,6 +125,13 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> impleme
}
@Override
public Device selectDeviceByDevId(String devId) {
LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper();
queryWrapper.eq(Device::getDevId, devId);
return deviceMapper.selectOne(queryWrapper);
}
@Override
public List<Device> notRoomIdList(Device device) {
SRoom room = roomMapper.selectSRoomById(device.getRoomId());
if (room != null) {
......
package share.system.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
......@@ -11,14 +13,13 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import share.common.constant.MqttConstants;
import share.common.core.redis.RedisUtil;
import share.common.enums.*;
import share.common.utils.DateUtils;
import share.system.domain.*;
import share.system.domain.vo.MqttxVo;
import share.system.mapper.DeviceGatewayMapper;
import share.system.mapper.DeviceLogMapper;
import share.system.mapper.DeviceMapper;
import share.system.mapper.DeviceStatusLogMapper;
import share.system.mapper.*;
import share.system.service.DeviceOpService;
import share.system.service.DeviceStatusLogService;
import share.system.service.MqttxService;
......@@ -26,6 +27,7 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;
......@@ -45,9 +47,15 @@ public class MqttxServiceImpl implements MqttxService {
@Autowired
private DeviceLogMapper deviceLogMapper;
@Autowired
private SRoomMapper roomMapper;
@Autowired
private DeviceStatusLogService deviceStatusLogService;
@Value("${mqtt.device-op-last-time}")
private Integer deviceOpLastTime;
@Autowired
private RedisUtil redisUtil;
@Autowired
private DeviceOpService deviceOpService;
/**
* 清除网关锁id列表
......@@ -567,6 +575,7 @@ public class MqttxServiceImpl implements MqttxService {
// 设备信息
List<Device> list = new ArrayList<>();
for (Object o : array) {
try {
// 默认离线
String status = DeviceStatusEnum.DEVICE_OFFLINE.getCode();
JSONArray jsonArray = JSONUtil.parseArray(o);
......@@ -578,21 +587,21 @@ public class MqttxServiceImpl implements MqttxService {
int decimal = Integer.parseInt(statusStr);
String binary = Integer.toBinaryString(decimal);
String[] binaryArray = binary.split("(?<=\\G.)");
if(binaryArray.length > 0) {
if (binaryArray.length > 0) {
String bit0 = binaryArray[0];
if ("1".equals(bit0)) {
if(binaryArray.length > 2) {
if (binaryArray.length > 2) {
String bit2 = binaryArray[2];
if ("1".equals(bit2)) {
status = DeviceStatusEnum.DEVICE_ENERGIZE.getCode();
} else {
status = DeviceStatusEnum.DEVICE_OUTAGE.getCode();
}
} else if (dev != null){
} else if (dev != null) {
// 设备类型判断
if (DeviceType.DEVICE_0001.getCode().equals(dev.getDevType())) {
status = DeviceStatusEnum.DEVICE_OUTAGE.getCode();
} else if(DeviceType.DEVICE_CCEE.getCode().equals(dev.getDevType())) {
} else if (DeviceType.DEVICE_CCEE.getCode().equals(dev.getDevType())) {
status = DeviceStatusEnum.DEVICE_ONLINE.getCode();
}
}
......@@ -638,6 +647,10 @@ public class MqttxServiceImpl implements MqttxService {
device.setStatus(status);
device.setUpdateTime(DateUtils.getNowDate());
list.add(device);
} catch (Exception e) {
// 解析异常跳出循环
continue;
}
}
// 插入设备变更记录
deviceStatusLogService.saveBatch(statusLogs);
......@@ -658,15 +671,105 @@ public class MqttxServiceImpl implements MqttxService {
if (json.size() > 0) {
JSONArray array = json.getJSONArray("params");
if (array != null && array.size() > 0) {
DeviceLog deviceLog = new DeviceLog();
String seq = json.getStr("seq");
deviceLog.setSeq(seq);
String result = array.getStr(1);
DeviceLog deviceLog = deviceLogMapper.selectDeviceLogOneBySeqMax(seq);
// 状态10代表网关接到消息响应,不做处理;另外还会有一条操作结果响应数据
if (deviceLog != null && !"10".equals(result)) {
if ("0".equals(result)) {
// 成功
this.sendMqttTopic(deviceLog.getDevId(), 2);
} else {
// 失败
if (deviceLog.getAfreshNum() != null && deviceLog.getAfreshNum() < 3) {
this.sendMqttTopic(deviceLog.getDevId(), 1);
} else {
// 失败3次后不重复发送,执行下一条
this.sendMqttTopic(deviceLog.getDevId(), 2);
}
}
deviceLog.setRemark(payload);
deviceLog.setResult(array.getStr(1));
return 0 < deviceLogMapper.updateBySeq(deviceLog);
deviceLog.setResult(result);
deviceLog.setUpdateTime(DateUtil.date());
return 0 < deviceLogMapper.updateDeviceById(deviceLog);
}
}
}
return false;
}
/**
* mqtt监控返回消息调用
* @param devId 设备id
* @param type 类型:1-失败,2-成功
*/
private void sendMqttTopic(String devId, Integer type) {
LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper();
queryWrapper.eq(Device::getDevId, devId);
Device device = deviceMapper.selectOne(queryWrapper);
if (device != null) {
LambdaQueryWrapper<SRoom> queryRoomWrapper = new LambdaQueryWrapper();
queryRoomWrapper.eq(SRoom::getId, device.getRoomId());
SRoom room = roomMapper.selectOne(queryRoomWrapper);
if (room != null) {
String key = StrUtil.concat(true, MqttConstants.MQTT_REDIS_KEY,
StrUtil.toString(room.getStoreId()));
// 如果成功,先删除当前数据缓存
if (type == 2) {
// 发送成功或者失败超过3次,删除当前消息,发送下一条
redisUtil.getRightPop(key, 10L);
}
// 获取当前需要发送的消息
Object data = redisUtil.getIndex(key, -1);
if (null != data) {
MqttxVo vo = BeanUtil.toBean(data, MqttxVo.class);
if (type == 1) {
// 失败重新发送,
// 更新发送次数,并修改重新加入队列
vo.setRefreshNum(vo.getRefreshNum() + 1);
vo.setSendSmsResult(0);
redisUtil.setListByIndex(key, -1, vo);
// 重新发送mqtt消息
// 异步执行, 间隔5秒
// 延时执行操作
this.supplyAsync(5L, vo, room.getStoreId());
} else if (type == 2) {
// 成功,发送下一条消息,发送mqtt消息
LambdaQueryWrapper<Device> query2Wrapper = new LambdaQueryWrapper();
query2Wrapper.eq(Device::getDevId, vo.getDevId());
Device dev = deviceMapper.selectOne(query2Wrapper);
// 先验证相同设备是否6秒内连续发送
long l = 1L;
String s = redisUtil.get(MqttConstants.MQTT_DEVICE_LAST_TIME_KEY + vo.getDevId());
if (StrUtil.isNotEmpty(s) && DeviceType.DEVICE_CCEE.getCode().equals(dev.getDevType())) {
long betweenDay = DateUtil.between(DateUtil.parseDateTime(s), DateUtil.date(), DateUnit.SECOND);
if (betweenDay < 10L) {
l = 10L - betweenDay;
}
}
System.out.println("测试设备消息间隔:"+ l);
// 异步执行
this.supplyAsync(l, vo, room.getStoreId());
}
}
}
}
}
private void supplyAsync(Long m, MqttxVo vo, Long storeId) {
CompletableFuture.supplyAsync(() -> {
// 延时执行操作
try {
Thread.sleep(m * 1000);
// 获取mqtt的topic、payload
deviceOpService.sendMqtt(vo, storeId);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Result: devId=" + vo.getDevId();
});
}
}
......@@ -7,6 +7,7 @@ import com.saobei.open.sdk.model.response.trade.SaobeiMiniPayResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import share.common.config.SaobeiConfig;
import share.common.config.WeChatConfig;
......@@ -54,6 +55,11 @@ public class OrderPayServiceImpl implements OrderPayService {
@Autowired
private SaobeiService saobeiService;
/**
* 获取域名
*/
@Value("${api.domain}")
private String apiDomain;
@Override
public OrderPayResultResponse payment(SOrder sOrder) {
......@@ -142,8 +148,6 @@ public class OrderPayServiceImpl implements OrderPayService {
* @return 微信预下单对象
*/
private CreateOrderRequestVo getUnifiedorderVo(SOrder sOrder, String openid, String appId, String mchId, String signKey) {
// 获取域名
String apiDomain = Constants.CONFIG_KEY_SITE_URL;
AttachVo attachVo = new AttachVo(OrderTypeEnum.getEnumByCode(sOrder.getOrderType()).getValue(), sOrder.getConsumerId());
CreateOrderRequestVo vo = new CreateOrderRequestVo();
......@@ -204,8 +208,6 @@ public class OrderPayServiceImpl implements OrderPayService {
* @return 预下单对象
*/
private SaobeiMiniPayRequestVo getSaobeiUnifiedOrderVo(SOrder sOrder, String openid, String appId, String mchId, String signKey) {
// 获取域名
String apiDomain = Constants.CONFIG_KEY_SITE_URL;
AttachVo attachVo = new AttachVo(OrderTypeEnum.getEnumByCode(sOrder.getOrderType()).getValue(), sOrder.getConsumerId());
SaobeiMiniPayRequestVo vo = new SaobeiMiniPayRequestVo();
......
......@@ -5,6 +5,7 @@ import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.saobei.open.sdk.model.response.trade.SaobeiTradeRefundResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import share.common.config.WeChatConfig;
import share.common.constant.Constants;
......@@ -53,6 +54,11 @@ public class OrderRefundServiceImpl extends ServiceImpl<SOrderMapper, SOrder> im
private ISConsumptionRecordsService sConsumptionRecordsService;
@Autowired
private ISRoomService roomService;
/**
* 获取域名
*/
@Value("${api.domain}")
private String apiDomain;
/**
* 退款 需要优化
......@@ -77,8 +83,7 @@ public class OrderRefundServiceImpl extends ServiceImpl<SOrderMapper, SOrder> im
String appId = weChatConfig.getAppId();
String mchId = weChatConfig.getMchId();
String signKey = weChatConfig.getSignKey();
String path = weChatConfig.getCertPath();
String apiDomain = Constants.CONFIG_KEY_SITE_URL;
String path = weChatConfig.getCertPath(); //TODO 商户证书路径p12(待提供)
//统一下单数据
WxRefundVo wxRefundVo = new WxRefundVo();
wxRefundVo.setAppid(appId);
......
......@@ -54,8 +54,8 @@ public class RoomStatusServiceImpl implements RoomStatusService {
// 通过门店及房间查询指定日期T+1的订单
List<SOrder> orderList = orderService.listByRoomInfo(storeId,new ArrayList<Long>(){{add(roomId);}},day);
SCleanRecords cleanRecords = cleanRecordsService.lastCleanByRoomId(roomId);
List<RoomStatusVo> voList = generatorRoomStatusList(store,roomId,orderList,cleanRecords,day,orderType);
voList.addAll(generatorRoomStatusList(store,roomId,orderList,cleanRecords,DateUtils.addDays(day,1),orderType));
List<RoomStatusVo> voList = generatorRoomStatusList(store,roomId,orderList,cleanRecords,day,orderType, user);
voList.addAll(generatorRoomStatusList(store,roomId,orderList,cleanRecords,DateUtils.addDays(day,1),orderType, user));
return voList;
}
......@@ -78,8 +78,8 @@ public class RoomStatusServiceImpl implements RoomStatusService {
List<RoomStatusVo> voList = new ArrayList<>();
Map<Long, SCleanRecords> finalCleanRecordMap = cleanRecordMap;
roomIds.stream().forEach(roomId -> {
voList.addAll(generatorRoomStatusList(store, roomId, orderMap.get(roomId), finalCleanRecordMap.get(roomId), day, OrderTypeEnum.RESERVER.getCode()));
voList.addAll(generatorRoomStatusList(store, roomId, orderMap.get(roomId), finalCleanRecordMap.get(roomId), DateUtils.addDays(day, 1), OrderTypeEnum.RESERVER.getCode()));
voList.addAll(generatorRoomStatusList(store, roomId, orderMap.get(roomId), finalCleanRecordMap.get(roomId), day, OrderTypeEnum.RESERVER.getCode(), user));
voList.addAll(generatorRoomStatusList(store, roomId, orderMap.get(roomId), finalCleanRecordMap.get(roomId), DateUtils.addDays(day, 1), OrderTypeEnum.RESERVER.getCode(), user));
});
return voList;
}
......@@ -87,7 +87,7 @@ public class RoomStatusServiceImpl implements RoomStatusService {
private List<RoomStatusVo> generatorRoomStatusList(SStore store,Long roomId,List<SOrder> orderList,SCleanRecords cleanRecords,Date day, Integer orderType){
private List<RoomStatusVo> generatorRoomStatusList(SStore store,Long roomId,List<SOrder> orderList,SCleanRecords cleanRecords,Date day, Integer orderType, SConsumer user){
String nowTime = "00:00";
String dayStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,day);
Boolean isToday = StringUtils.equals(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,day)
......@@ -111,19 +111,19 @@ public class RoomStatusServiceImpl implements RoomStatusService {
vo.setRoomId(roomId);
vo.setTimeHour(timeHour);
Date timeHourDate = DateUtils.parseDate(timeHour);
setTimeHourStatus(vo,timeHourDate,store,orderList,cleanRecords,dayStr,finalNowTime,isToday,orderType);
setTimeHourStatus(vo,timeHourDate,store,orderList,cleanRecords,dayStr,finalNowTime,isToday,orderType, user);
voList.add(vo);
});
return voList;
}
//设置时间段房间可预约状态(可预约:大于营业开始时间,小于营业结束时间,大于当前时间,当前时间没有订单)
private void setTimeHourStatus(RoomStatusVo vo,Date timeHourDate, SStore store, List<SOrder> orderList, SCleanRecords cleanRecords, String day, String finalNowTime, Boolean isToday, Integer orderType){
private void setTimeHourStatus(RoomStatusVo vo,Date timeHourDate, SStore store, List<SOrder> orderList, SCleanRecords cleanRecords, String day, String finalNowTime, Boolean isToday, Integer orderType, SConsumer user){
vo.setStatus(RoomStatusEnum.FREE.getValue());
checkTimeHourToSysDate(vo,timeHourDate,day,finalNowTime,isToday);
checkTimeHourToBusiness(vo,timeHourDate,store,day);
checkTimeHourToOrder(vo,timeHourDate,orderList,cleanRecords,orderType);
checkTimeHourToOrder(vo,timeHourDate,orderList,cleanRecords,orderType, user);
}
private void changeEndHoldTime(RoomStatusVo vo, Date date){
......@@ -184,8 +184,8 @@ public class RoomStatusServiceImpl implements RoomStatusService {
}
}
private void checkTimeHourToOrder(RoomStatusVo vo,Date timeHourDate, List<SOrder> orderList, SCleanRecords cleanRecords, Integer orderType){
SConsumer user = consumerService.getInfo();
private void checkTimeHourToOrder(RoomStatusVo vo,Date timeHourDate, List<SOrder> orderList, SCleanRecords cleanRecords, Integer orderType, SConsumer user){
// SConsumer user = consumerService.getInfo();
if(CollectionUtils.isNotEmpty(orderList)){
orderList.stream().forEach(order -> {
Date orderStartDate = Objects.nonNull(order.getStartDate())?order.getStartDate():order.getPreStartDate();
......
......@@ -71,8 +71,8 @@ public class SConsumerCouponServiceImpl extends ServiceImpl<SConsumerCouponMappe
public List<SConsumerCoupon> selectSConsumerCouponList(SConsumerCoupon sConsumerCoupon) {
List<SConsumerCoupon> sConsumerCoupons = baseMapper.selectSConsumerCouponList(sConsumerCoupon);
sConsumerCoupons.forEach(item -> {
List<SConsumer> list = sConsumerService.list();
sConsumerCoupons.forEach(item -> {
if (list.stream().filter(obj -> obj.getId().equals(item.getConsumerId())).findFirst().isPresent()) {
item.setPhone(list.stream().filter(obj -> obj.getId().equals(item.getConsumerId())).findFirst().get().getPhone());
if (StringUtils.isNotBlank(list.stream().filter(obj -> obj.getId().equals(item.getConsumerId())).findFirst().get().getNickName())) {
......
......@@ -5,6 +5,7 @@ import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.util.ObjectUtil;
......@@ -14,11 +15,7 @@ import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dianping.openapi.sdk.api.tuangou.TuangouReceiptGetConsumed;
import com.dianping.openapi.sdk.api.tuangou.entity.TuangouReceiptGetConsumedReponse;
import com.dianping.openapi.sdk.api.tuangou.entity.TuangouReceiptGetConsumedReponseEntity;
import com.dianping.openapi.sdk.api.tuangou.entity.TuangouReceiptGetConsumedRequest;
import com.dianping.openapi.sdk.httpclient.DefaultOpenAPIClient;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
......@@ -34,6 +31,7 @@ import share.common.utils.DateUtil;
import share.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import share.common.utils.SecurityUtils;
import share.common.utils.bean.BeanUtils;
import share.system.domain.*;
import share.system.domain.vo.*;
......@@ -104,6 +102,8 @@ public class SOrderServiceImpl extends ServiceImpl<SOrderMapper, SOrder> impleme
@Autowired
private ISCleanRecordsService cleanRecordsService;
private final static Long FIVE = 5l;
/**
* 查询订单
......@@ -235,6 +235,50 @@ public class SOrderServiceImpl extends ServiceImpl<SOrderMapper, SOrder> impleme
return Boolean.FALSE;
}
@Override
public int modifyOrder(SOrderDto sOrderDto) {
SOrder sOrder = baseMapper.selectOne(new LambdaQueryWrapper<SOrder>().eq(SOrder::getOrderNo, sOrderDto.getOrderNo()));
if (ObjectUtil.isEmpty(sOrder)) {
throw new BaseException("订单不存在");
}
if (OrderStatusEnum.INUSE.getCode().equals(sOrder.getStatus())) {
//订单为以开始,修改房间状态
SRoom sRoom = new SRoom();
sRoom.setId(sOrder.getRoomId());
sRoom.setStatus(RoomStatusEnum.FREE.getValue());
roomService.updateById(sRoom);
if (ObjectUtil.isNotEmpty(sOrder.getArrivalTime())) {
deviceOpService.actionExecute(sOrder.getRoomId(), sOrder.getConsumerPhone(), VoiceEnum.SEND_CUSTOMER.getCode(),
cn.hutool.core.date.DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN),
cn.hutool.core.date.DateUtil.format(cn.hutool.core.date.DateUtil.offsetMinute(new Date(), 1), DatePattern.NORM_DATETIME_PATTERN), "1");
//延时5秒断电
deviceOpService.openOrCloseDevice(sOrder.getRoomId(), sOrder.getConsumerPhone(), OpTypeEnum.CUT_ELECTRIC.getCode(), true, FIVE);
}
}
//当前时间加90分钟
Date date = DateUtils.addMinutes(new Date(), 90);
sOrder.setPreStartDate(date);
sOrder.setPreEndDate(date);
sOrder.setStatus(OrderStatusEnum.UNUSED.getCode());
if (ObjectUtil.isNotEmpty(sOrder.getCouponId())) {
SConsumerCoupon sConsumerCoupon = consumerCouponService.selectSConsumerCouponById(sOrder.getCouponId());
if (sOrderDto.getIsReverseconsume().equals(YesNoEnum.yes.getIndex())) {
sConsumerCoupon.setUseStatus(CouponStatusEnum.EXPIRED.getValue());
} else {
sConsumerCoupon.setUseStatus(CouponStatusEnum.NORMAL.getValue());
}
consumerCouponService.updateById(sConsumerCoupon);
sOrder.setCouponId(null);
}
sOrder.setUpdateBy(SecurityUtils.getUsername());
//年月日时分秒
sOrder.setRemark(sOrderDto.getRemark());
sOrder.setUpdateTime(new Date());
redisUtil.delete(ReceiptRdeisEnum.ORDER_NO.getValue() + sOrderDto.getOrderNo());
redisUtil.delete(ReceiptRdeisEnum.ORDER_NO_KEY.getValue() + sOrderDto.getOrderNo());
return baseMapper.updateSOrder(sOrder);
}
/**
* 新增订单
*
......@@ -886,6 +930,8 @@ public class SOrderServiceImpl extends ServiceImpl<SOrderMapper, SOrder> impleme
throw new BaseException("微信申请退款失败!");
}
}else {
// 删除redis 缓存信息,防止退款订单自动开始及给用户发送提示短信
redisUtil.delete(ReceiptRdeisEnum.ORDER_NO.getValue() + sOrder.getOrderNo());
//修改订单退款状态,退款成功
sOrder.setStatus(OrderStatusEnum.CANCEL.getCode());
sOrder.setRefundStatus(RefundStatusEnum.REFUNDED.getCode());
......@@ -1033,6 +1079,23 @@ public class SOrderServiceImpl extends ServiceImpl<SOrderMapper, SOrder> impleme
if (DateUtils.addHours(sOrder.getPreStartDate(), Constants.OPEN_DOOR_AHEAD_HOUR_MINUS).compareTo(new Date()) > 0) {
throw new BaseException("预约时间未到达,可提前" + Constants.OPEN_DOOR_AHEAD_HOUR + "小时进场,请耐心等候!");
}
// 判断房间是否脏房中
// if (sRoomVo.getIsDirtyRoom() > 0) {
// throw new BaseException("当前房间未保洁,请等待!");
// }
// 55分钟内是否有保洁记录
LambdaQueryWrapper<SCleanRecords> recordsQueryWrapper = new LambdaQueryWrapper<>();
recordsQueryWrapper.eq(SCleanRecords::getRoomId, sOrder.getRoomId());
recordsQueryWrapper.ge(SCleanRecords::getCreateTime, cn.hutool.core.date.DateUtil.offset(cn.hutool.core.date.DateUtil.date(), DateField.MINUTE, -60));
List<SCleanRecords> recordsList = cleanRecordsService.list(recordsQueryWrapper);
if(recordsList != null && recordsList.size() > 0) {
SCleanRecords records = recordsList.get(0);
if (CleaningStatusEnum.CLEANED.getCode().equals(records.getStatus())) {
// 如果保洁状态未不是保洁中
throw new BaseException("当前房间待保洁中,请等待!");
}
}
//更改订单状态,房间状态,开始时间,结束时间
sOrder.setStatus(OrderStatusEnum.INUSE.getCode());
//计算预约开始和结束时间时长
......
......@@ -15,6 +15,7 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import share.common.config.WeChatConfig;
import share.common.constant.PayConstants;
......@@ -70,6 +71,9 @@ public class WechatNewServiceImpl implements WechatNewService {
@Autowired
private ISRoomService roomService;
@Value("${wechat.miniprogram_state}")
private String miniprogramState;
/**
* 获取公众号accessToken
*/
......@@ -106,8 +110,18 @@ public class WechatNewServiceImpl implements WechatNewService {
boolean exists = redisUtil.exists(WeChatConstants.REDIS_WECAHT_MINI_ACCESS_TOKEN_KEY);
if (exists) {
Object accessToken = redisUtil.get(WeChatConstants.REDIS_WECAHT_MINI_ACCESS_TOKEN_KEY);
try {
int code = sensitiveCheck(accessToken.toString(), "验证token是否过期");
if(code == WeChatConstants.WECHAT_TOKEN_EXPIRED_CODE){
exists = false;
}
}catch (Exception e){
throw new BaseException("验证token是否过期接口异常");
}
if(exists) {
return accessToken.toString();
}
}
String appId = weChatConfig.getAppId();
if (StrUtil.isBlank(appId)) {
throw new BaseException("微信小程序appId未设置");
......@@ -123,6 +137,24 @@ public class WechatNewServiceImpl implements WechatNewService {
return accessTokenVo.getAccessToken();
}
/**
* <a href="https://developers.weixin.qq.com/minigame/dev/wxcloudrun/src/guide/weixin/token.html">敏感词检测</a>
*
* @param token access_token
* @param content content
* @return errcode
*/
public int sensitiveCheck(String token, String content) throws Exception {
Map<String, String> paramMap = new HashMap<>(1);
paramMap.put("content", content);
String url = StrUtil.format("https://api.weixin.qq.com/wxa/msg_sec_check?access_token={}", token);
String result = restTemplateUtil.getData(url,paramMap);
JSONObject jsonObject = JSONObject.parseObject(result);
return jsonObject.getInteger("errcode");
}
/**
* 获取开放平台access_token
* 通过 code 获取
......@@ -155,6 +187,10 @@ public class WechatNewServiceImpl implements WechatNewService {
return JSONObject.parseObject(data.toJSONString(), WeChatOauthToken.class);
}
/**
* 获取开放平台用户信息
*
......@@ -535,7 +571,7 @@ public class WechatNewServiceImpl implements WechatNewService {
//测试页面
String url = "/pages/orderResult/orderResult?orderNo=" + byOrderNo.getOrderNo();
templateMessageVo.setPage(url);
templateMessageVo.setMiniprogram_state("trial");
templateMessageVo.setMiniprogram_state(miniprogramState);
HashMap<String, SendTemplateMessageItemVo> data = new HashMap<>();
SStore sStore = storeService.getById(byOrderNo.getStoreId());
SRoomVo sRoomVo = roomService.selectSRoomById(byOrderNo.getRoomId());
......@@ -994,6 +1030,9 @@ public class WechatNewServiceImpl implements WechatNewService {
return JSONObject.parseObject(data.toJSONString(), WeChatAccessTokenVo.class);
}
/**
* 微信异常处理
*
......
......@@ -20,12 +20,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="remark" column="remark" />
<result property="result" column="result" />
<result property="description" column="description" />
<result property="afreshNum" column="afresh_num" />
</resultMap>
<sql id="selectDeviceLogVo">
select s1.id, s1.dev_mac, s1.dev_id, s1.seq, s1.mqtt_type, s1.mqtt_describe, s1.payload, s1.topic,
s1.create_by, s1.create_time,
s1.update_by, s1.update_time, s1.remark, s1.`result`, s1.description
s1.update_by, s1.update_time, s1.remark, s1.`result`, s1.description, s1.afresh_num
from s_device_log s1
left join s_device s2 on s1.dev_id = s2.dev_id
left join s_room s3 on s2.room_id = s3.id
......@@ -48,7 +49,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
t1.update_time,
t1.remark,
t1.`result`,
t1.description
t1.description, t1.afresh_num
from s_device_log t1
join s_device t2 on t1.dev_id = t2.dev_id
join s_room t3 on t2.room_id = t3.id
......@@ -67,6 +68,26 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
order by create_time desc
</select>
<select id="selectDeviceLogOneBySeqMax" parameterType="String" resultMap="DeviceLogResult">
select
t1.id,
t1.dev_mac,
t1.dev_id,
t1.seq,
t1.mqtt_type,
t1.mqtt_describe,
t1.payload,
t1.topic,
t1.create_by,
t1.create_time,
t1.update_by,
t1.update_time,
t1.remark,
t1.`result`,
t1.description, t1.afresh_num
from s_device_log t1 where seq = #{seq} order by t1.afresh_num desc limit 0,1
</select>
<select id="selectDeviceLogById" parameterType="Long" resultMap="DeviceLogResult">
<include refid="selectDeviceLogVo"/>
where s1.id = #{id}
......@@ -74,7 +95,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<select id="selectListByMaxId" resultMap="DeviceLogResult">
SELECT t1.id, t1.dev_mac, t1.dev_id, t1.seq, t1.mqtt_type, t1.mqtt_describe, t1.payload, t1.topic,
t1.create_by, t1.create_time, t1.update_by, t1.update_time, t1.remark,
t1.`result`, t1.description
t1.`result`, t1.description, t1.afresh_num
FROM s_device_log t1
JOIN (
SELECT MAX(id) AS max_id
......@@ -106,6 +127,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="remark != null">remark,</if>
<if test="result != null">`result`,</if>
<if test="description != null">description,</if>
<if test="afreshNum != null">afresh_num,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="devMac != null">#{devMac},</if>
......@@ -122,6 +144,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="remark != null">#{remark},</if>
<if test="result != null">#{result},</if>
<if test="description != null">#{description},</if>
<if test="afreshNum != null">#{afreshNum},</if>
</trim>
</insert>
......@@ -142,6 +165,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="remark != null">remark = #{remark},</if>
<if test="result != null">`result` = #{result},</if>
<if test="description != null">description = #{description},</if>
<if test="afreshNum != null">afresh_num = #{afreshNum},</if>
</trim>
where id = #{id}
</update>
......@@ -151,6 +175,12 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
where seq = #{seq}
</update>
<update id="updateDeviceById" parameterType="DeviceLog">
update s_device_log
set remark = #{remark},`result` = #{result}, update_time = #{updateTime}
where id = #{id}
</update>
<delete id="deleteDeviceLogById" parameterType="Long">
delete from s_device_log where id = #{id}
</delete>
......
......@@ -225,7 +225,7 @@
<if test="consumerPhone != null">consumer_phone = #{consumerPhone},</if>
<if test="packId != null">pack_id = #{packId},</if>
<if test="packPrice != null">pack_price = #{packPrice},</if>
<if test="couponId != null">coupon_id = #{couponId},</if>
<if test="couponId != ''">coupon_id = #{couponId},</if>
<if test="couponPrice != null">coupon_price = #{couponPrice},</if>
<if test="totalPrice != null">total_price = #{totalPrice},</if>
<if test="payPrice != null">pay_price = #{payPrice},</if>
......
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