+13
@@ -37,4 +37,17 @@ public class WechatMiniProperties {
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private Integer accessTokenBufferSeconds = 60;
|
||||
|
||||
/** 订阅消息发送开关。 */
|
||||
private Boolean subscribeMessageEnabled = true;
|
||||
/** DEV 使用 mock,SIT/PROD 使用 wechat。 */
|
||||
private String subscribeMessageProvider = "mock";
|
||||
/** 服务开始提醒提前分钟数。 */
|
||||
private Integer serviceStartReminderLeadMinutes = 30;
|
||||
/** 订阅消息点击后的默认页面。 */
|
||||
private String subscribeMessagePage = "/pages/planning/index";
|
||||
/** 微信小程序消息跳转环境。 */
|
||||
private String subscribeMessageMiniprogramState = "developer";
|
||||
/** 发送失败后的最大重试次数。 */
|
||||
private Integer subscribeMessageMaxRetries = 3;
|
||||
}
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.integration.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 微信订阅消息发送记录。 */
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@TableName("t_wechat_subscribe_message_log")
|
||||
public class WechatSubscribeMessageLogDO extends BaseEntity {
|
||||
private String eventKey;
|
||||
private String templateCode;
|
||||
private Long userId;
|
||||
private Long orderId;
|
||||
private Long orderItemId;
|
||||
private String openIdHash;
|
||||
private String status;
|
||||
private Integer retryCount;
|
||||
private Integer errCode;
|
||||
private String errMsg;
|
||||
private LocalDateTime nextRetryTime;
|
||||
private LocalDateTime sentTime;
|
||||
private Integer isDelete;
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.integration.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatSubscribeMessageLogDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface WechatSubscribeMessageLogMapper extends BaseMapper<WechatSubscribeMessageLogDO> {
|
||||
@Select("SELECT * FROM t_wechat_subscribe_message_log WHERE is_delete = 0 AND ((status IN ('PENDING','RETRY') AND (next_retry_time IS NULL OR next_retry_time <= #{now})) OR (status = 'PROCESSING' AND update_time < DATE_SUB(#{now}, INTERVAL 10 MINUTE))) ORDER BY id ASC LIMIT #{limit}")
|
||||
List<WechatSubscribeMessageLogDO> selectDue(@Param("now") LocalDateTime now, @Param("limit") int limit);
|
||||
|
||||
@Update("UPDATE t_wechat_subscribe_message_log SET status = 'PROCESSING', update_time = NOW() WHERE id = #{id} AND is_delete = 0 AND (status IN ('PENDING','RETRY') OR (status = 'PROCESSING' AND update_time < DATE_SUB(NOW(), INTERVAL 10 MINUTE)))")
|
||||
int claimForProcessing(@Param("id") Long id);
|
||||
}
|
||||
+8
@@ -1,5 +1,6 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.integration.service;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 微信小程序开放接口客户端。
|
||||
@@ -31,6 +32,13 @@ public interface WechatMiniClientService {
|
||||
|
||||
String getAccessTokenForContentModeration();
|
||||
|
||||
/** 发送微信小程序订阅消息。 */
|
||||
SubscribeMessageResult sendSubscribeMessage(String openId, String templateId, Map<String, String> data,
|
||||
String page, String miniprogramState);
|
||||
|
||||
record SubscribeMessageResult(boolean success, int errCode, String errMsg) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `SessionInfo`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.integration.service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** Salon 微信订阅消息业务服务。 */
|
||||
public interface WechatSubscribeMessageService {
|
||||
String TEMPLATE_SERVICE_START = "jURyVPL52qyUhm_c_OyvED5zivUZr_3LfAXjfV-KOJc";
|
||||
String TEMPLATE_CANCELLED = "0v80O2xaOS8D_aSrurqTo4fds8FmyMlEOsy66LXsjNQ";
|
||||
String TEMPLATE_APPOINTMENT = "Dmebp1afiB9U5rw_ASKiMEQWIqYNF8bSM4JPR4PZ5eo";
|
||||
|
||||
void enqueueAppointmentReminder(Long orderId, Long orderItemId);
|
||||
|
||||
void enqueueCancellationNotice(Long orderId, Long orderItemId);
|
||||
|
||||
void enqueueServiceStartReminder(Long orderId, Long orderItemId, LocalDateTime appointmentTime);
|
||||
|
||||
void processDueMessages();
|
||||
}
|
||||
+42
@@ -20,6 +20,7 @@ import org.springframework.web.util.UriComponentsBuilder;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* WeChat mini program API client.
|
||||
@@ -206,6 +207,47 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService {
|
||||
return getAccessToken();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubscribeMessageResult sendSubscribeMessage(String openId, String templateId, Map<String, String> data,
|
||||
String page, String miniprogramState) {
|
||||
if (!StringUtils.hasText(openId) || !StringUtils.hasText(templateId)) {
|
||||
return new SubscribeMessageResult(false, 40001, "缺少订阅消息接收人或模板");
|
||||
}
|
||||
if (!Boolean.TRUE.equals(properties.getSubscribeMessageEnabled())) {
|
||||
return new SubscribeMessageResult(false, 40002, "订阅消息已关闭");
|
||||
}
|
||||
if ("mock".equalsIgnoreCase(properties.getSubscribeMessageProvider())) {
|
||||
return new SubscribeMessageResult(true, 0, "MOCK_OK");
|
||||
}
|
||||
try {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
Map<String, Object> request = new HashMap<>();
|
||||
request.put("touser", openId);
|
||||
request.put("template_id", templateId);
|
||||
request.put("page", StringUtils.hasText(page) ? page : "/pages/planning/index");
|
||||
request.put("miniprogram_state", StringUtils.hasText(miniprogramState) ? miniprogramState : "developer");
|
||||
request.put("lang", "zh_CN");
|
||||
Map<String, Map<String, String>> templateData = new HashMap<>();
|
||||
if (data != null) {
|
||||
data.forEach((key, value) -> templateData.put(key, Map.of("value", value == null ? "-" : value)));
|
||||
}
|
||||
request.put("data", templateData);
|
||||
Map<String, Object> response = readJsonResponse(
|
||||
doPostForString(
|
||||
UriComponentsBuilder.fromHttpUrl("https://api.weixin.qq.com/cgi-bin/message/subscribe/send")
|
||||
.queryParam("access_token", getAccessToken()).build(true).toUriString(),
|
||||
new HttpEntity<>(request, headers), "发送微信订阅消息失败"),
|
||||
"发送微信订阅消息失败");
|
||||
int errCode = (int) parseLong(response.get("errcode"), 0L);
|
||||
String errMsg = asText(response.get("errmsg"));
|
||||
return new SubscribeMessageResult(errCode == 0, errCode, errMsg);
|
||||
} catch (RuntimeException exception) {
|
||||
// 订阅消息属于异步通知,微信暂时不可用时交给 Outbox 重试,不影响预约主流程。
|
||||
return new SubscribeMessageResult(false, -1, "微信订阅消息服务暂时不可用");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load data by the supplied parameter.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.integration.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatSubscribeMessageLogDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatSubscribeMessageLogMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatSubscribeMessageService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class WechatSubscribeMessageServiceImpl implements WechatSubscribeMessageService {
|
||||
/** 微信 date 类型使用中文日期格式;time 类型单独使用 HH:mm。 */
|
||||
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
|
||||
private static final DateTimeFormatter CLOCK_TIME = DateTimeFormatter.ofPattern("HH:mm");
|
||||
private static final String PENDING = "PENDING";
|
||||
private static final String RETRY = "RETRY";
|
||||
private static final String SENT = "SENT";
|
||||
private static final String FAILED = "FAILED";
|
||||
|
||||
private final WechatSubscribeMessageLogMapper logMapper;
|
||||
private final WechatMiniBindingMapper bindingMapper;
|
||||
private final WechatMiniClientService wechatMiniClientService;
|
||||
private final WechatMiniProperties properties;
|
||||
private final OrderMapper orderMapper;
|
||||
private final OrderItemMapper orderItemMapper;
|
||||
private final ProductMapper productMapper;
|
||||
private final UserMapper userMapper;
|
||||
private final PhoneCrypto phoneCrypto;
|
||||
|
||||
@Override
|
||||
public void enqueueAppointmentReminder(Long orderId, Long orderItemId) {
|
||||
enqueue("APPOINTMENT", TEMPLATE_APPOINTMENT, orderId, orderItemId, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enqueueCancellationNotice(Long orderId, Long orderItemId) {
|
||||
enqueue("CANCELLED", TEMPLATE_CANCELLED, orderId, orderItemId, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enqueueServiceStartReminder(Long orderId, Long orderItemId, LocalDateTime appointmentTime) {
|
||||
enqueue("SERVICE_START", TEMPLATE_SERVICE_START, orderId, orderItemId, appointmentTime);
|
||||
}
|
||||
|
||||
private void enqueue(String eventType, String templateCode, Long orderId, Long orderItemId, LocalDateTime dueTime) {
|
||||
if (!Boolean.TRUE.equals(properties.getSubscribeMessageEnabled()) || orderItemId == null) return;
|
||||
OrderItemDO item = orderItemMapper.selectById(orderItemId);
|
||||
if (item == null || item.getArtistId() == null) return;
|
||||
String eventKey = eventType + ":" + orderItemId + ":" + item.getArtistId()
|
||||
+ (dueTime == null ? "" : ":" + dueTime);
|
||||
WechatSubscribeMessageLogDO log = new WechatSubscribeMessageLogDO();
|
||||
log.setEventKey(eventKey);
|
||||
log.setTemplateCode(templateCode);
|
||||
log.setOrderId(orderId);
|
||||
log.setOrderItemId(orderItemId);
|
||||
log.setUserId(item.getArtistId());
|
||||
log.setStatus(PENDING);
|
||||
log.setRetryCount(0);
|
||||
log.setNextRetryTime(dueTime == null ? LocalDateTime.now() : dueTime.minusMinutes(Math.max(1, properties.getServiceStartReminderLeadMinutes() == null ? 30 : properties.getServiceStartReminderLeadMinutes())));
|
||||
log.setIsDelete(0);
|
||||
try { logMapper.insert(log); } catch (DuplicateKeyException ignored) { }
|
||||
}
|
||||
|
||||
@Override
|
||||
@Scheduled(fixedDelayString = "${jayucloud-salon.wechat.mini.subscribe-message-scan-delay-millis:60000}")
|
||||
public void processDueMessages() {
|
||||
if (!Boolean.TRUE.equals(properties.getSubscribeMessageEnabled())) return;
|
||||
List<WechatSubscribeMessageLogDO> logs = logMapper.selectDue(LocalDateTime.now(), 50);
|
||||
for (WechatSubscribeMessageLogDO log : logs) {
|
||||
if (logMapper.claimForProcessing(log.getId()) != 1) continue;
|
||||
try {
|
||||
processOne(log);
|
||||
} catch (RuntimeException exception) {
|
||||
retry(log, -1, "订阅消息处理暂时失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void processOne(WechatSubscribeMessageLogDO log) {
|
||||
OrderItemDO item = orderItemMapper.selectById(log.getOrderItemId());
|
||||
OrderDO order = item == null ? null : orderMapper.selectById(item.getOrderId());
|
||||
if (item == null || order == null || Integer.valueOf(1).equals(item.getIsDelete()) || Integer.valueOf(1).equals(order.getIsDelete())) {
|
||||
mark(log, FAILED, 40004, "预约不存在", null); return;
|
||||
}
|
||||
if (log.getUserId() != null && !log.getUserId().equals(item.getArtistId())) {
|
||||
mark(log, FAILED, 40008, "预约承接美甲师已变化", null); return;
|
||||
}
|
||||
if (TEMPLATE_SERVICE_START.equals(log.getTemplateCode()) && (item.getAppointmentTime() == null || !Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()))) {
|
||||
mark(log, FAILED, 40005, "预约已取消或状态已变化", null); return;
|
||||
}
|
||||
if (TEMPLATE_SERVICE_START.equals(log.getTemplateCode()) && !item.getAppointmentTime().isAfter(LocalDateTime.now())) {
|
||||
mark(log, FAILED, 40011, "预约已开始,跳过开始提醒", null); return;
|
||||
}
|
||||
if (TEMPLATE_SERVICE_START.equals(log.getTemplateCode())
|
||||
&& !log.getEventKey().endsWith(String.valueOf(item.getAppointmentTime()))) {
|
||||
mark(log, FAILED, 40008, "预约时间已变化", null); return;
|
||||
}
|
||||
if (TEMPLATE_APPOINTMENT.equals(log.getTemplateCode()) && !Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) {
|
||||
mark(log, FAILED, 40009, "预约已不在待服务状态", null); return;
|
||||
}
|
||||
if (TEMPLATE_CANCELLED.equals(log.getTemplateCode()) && !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus())) {
|
||||
mark(log, FAILED, 40010, "预约取消状态已变化", null); return;
|
||||
}
|
||||
Long artistId = item.getArtistId();
|
||||
if (artistId == null) { mark(log, FAILED, 40006, "预约尚未分配美甲师", null); return; }
|
||||
UserDO artist = userMapper.selectById(artistId);
|
||||
if (artist == null) { mark(log, FAILED, 40007, "美甲师不存在", null); return; }
|
||||
LambdaQueryWrapper<WechatMiniBindingDO> bindingQuery = new LambdaQueryWrapper<WechatMiniBindingDO>()
|
||||
.eq(WechatMiniBindingDO::getUserId, artistId)
|
||||
.eq(WechatMiniBindingDO::getStatus, 1);
|
||||
if (StringUtils.hasText(properties.getAppId())) {
|
||||
bindingQuery.eq(WechatMiniBindingDO::getAppId, properties.getAppId());
|
||||
}
|
||||
WechatMiniBindingDO binding = bindingMapper.selectOne(bindingQuery.last("LIMIT 1"));
|
||||
if (binding == null || !StringUtils.hasText(binding.getOpenId())) { mark(log, FAILED, 43101, "美甲师未授权订阅消息", null); return; }
|
||||
log.setUserId(artistId);
|
||||
log.setOpenIdHash(phoneCrypto.index(binding.getOpenId()));
|
||||
logMapper.updateById(log);
|
||||
ProductDO product = item.getProductId() == null ? null : productMapper.selectById(item.getProductId());
|
||||
String productTitle = clip(product == null ? "预约服务" : product.getTitle(), 20);
|
||||
String customerName = clip(StringUtils.hasText(order.getCustomerNameSnapshot()) ? order.getCustomerNameSnapshot() : "到店客户", 20);
|
||||
String dateTime = item.getAppointmentTime() == null ? "待确认" : DATE_TIME.format(item.getAppointmentTime());
|
||||
String clockTime = item.getAppointmentTime() == null ? "待确认" : CLOCK_TIME.format(item.getAppointmentTime());
|
||||
Map<String, String> data = new LinkedHashMap<>();
|
||||
if (TEMPLATE_SERVICE_START.equals(log.getTemplateCode())) {
|
||||
data.put("thing1", "预约即将开始,请提前准备"); data.put("date3", clip(dateTime, 20)); data.put("thing6", productTitle); data.put("thing7", customerName);
|
||||
} else if (TEMPLATE_CANCELLED.equals(log.getTemplateCode())) {
|
||||
data.put("name1", clip(customerName, 10)); data.put("thing2", productTitle); data.put("time4", clip(clockTime, 20)); data.put("thing6", clip(StringUtils.hasText(order.getCancelReason()) ? order.getCancelReason() : "门店取消预约", 20));
|
||||
} else {
|
||||
data.put("thing1", productTitle); data.put("time2", clip(clockTime, 20)); data.put("thing3", "请提前确认服务安排"); data.put("name5", clip(StringUtils.hasText(artist.getNickname()) ? artist.getNickname() : artist.getAccount(), 10)); data.put("name6", clip(customerName, 10));
|
||||
}
|
||||
WechatMiniClientService.SubscribeMessageResult result = wechatMiniClientService.sendSubscribeMessage(binding.getOpenId(), log.getTemplateCode(), data, properties.getSubscribeMessagePage(), properties.getSubscribeMessageMiniprogramState());
|
||||
if (result.success()) mark(log, SENT, 0, result.errMsg(), LocalDateTime.now());
|
||||
else if (isPermanentWechatError(result.errCode())) mark(log, FAILED, result.errCode(), result.errMsg(), null);
|
||||
else retry(log, result.errCode(), result.errMsg());
|
||||
}
|
||||
|
||||
private boolean isPermanentWechatError(int code) {
|
||||
return code == 40001 || code == 40003 || code == 40004 || code == 40037
|
||||
|| code == 41028 || code == 41030 || code == 43101 || code == 47003;
|
||||
}
|
||||
|
||||
private void retry(WechatSubscribeMessageLogDO log, int code, String message) {
|
||||
int count = log.getRetryCount() == null ? 0 : log.getRetryCount();
|
||||
int max = properties.getSubscribeMessageMaxRetries() == null ? 3 : properties.getSubscribeMessageMaxRetries();
|
||||
if (count >= max) { mark(log, FAILED, code, message, null); return; }
|
||||
mark(log, RETRY, code, message, LocalDateTime.now().plusSeconds(10L * (count + 1)));
|
||||
}
|
||||
|
||||
private void mark(WechatSubscribeMessageLogDO log, String status, int code, String message, LocalDateTime time) {
|
||||
log.setStatus(status); log.setErrCode(code); log.setErrMsg(clip(message, 500)); log.setNextRetryTime(time);
|
||||
if (SENT.equals(status)) log.setSentTime(LocalDateTime.now());
|
||||
log.setRetryCount(log.getRetryCount() == null ? 0 : log.getRetryCount() + (RETRY.equals(status) ? 1 : 0));
|
||||
logMapper.updateById(log);
|
||||
}
|
||||
|
||||
private static String clip(String value, int max) {
|
||||
if (!StringUtils.hasText(value)) return "-";
|
||||
String text = value.trim(); return text.length() <= max ? text : text.substring(0, max);
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -107,9 +107,11 @@ public class OrderController {
|
||||
* @param request parameter `request` supplied by the caller
|
||||
* @return Result<Void> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
public Result<Void> cancelOrder(@PathVariable Long orderId, HttpServletRequest request) {
|
||||
public Result<Void> cancelOrder(@PathVariable Long orderId,
|
||||
@RequestParam(required = false) String cancelReason,
|
||||
HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
orderService.cancelOrder(orderId, userId);
|
||||
orderService.cancelOrder(orderId, userId, cancelReason);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -57,6 +57,7 @@ public class OrderDO extends BaseEntity {
|
||||
private String paymentOrderNo;
|
||||
private String refundStatus;
|
||||
private String customerRemark;
|
||||
private String cancelReason;
|
||||
private String customerNameSnapshot;
|
||||
@TableField(typeHandler = PhoneEncryptionTypeHandler.class)
|
||||
private String customerPhoneSnapshot;
|
||||
|
||||
+5
-1
@@ -50,7 +50,11 @@ public interface OrderService {
|
||||
* @param orderId parameter `orderId` supplied by the caller
|
||||
* @param userId parameter `userId` supplied by the caller
|
||||
*/
|
||||
void cancelOrder(Long orderId, Long userId);
|
||||
default void cancelOrder(Long orderId, Long userId) {
|
||||
cancelOrder(orderId, userId, null);
|
||||
}
|
||||
|
||||
void cancelOrder(Long orderId, Long userId, String cancelReason);
|
||||
/**
|
||||
* Run business method `processOrder`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
|
||||
+33
@@ -41,6 +41,7 @@ import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.mapper.AppointmentReservationMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.service.AppointmentCapacityService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.BusinessEventOutboxService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatSubscribeMessageService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CouponService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.service.TagService;
|
||||
@@ -432,6 +433,9 @@ public class OrderServiceImpl implements OrderService {
|
||||
@Resource
|
||||
private AppointmentReservationMapper appointmentReservationMapper;
|
||||
|
||||
@Resource
|
||||
private WechatSubscribeMessageService wechatSubscribeMessageService;
|
||||
|
||||
@PreDestroy
|
||||
/**
|
||||
* Run business method `shutdownOrderLockRenewExecutor`.
|
||||
@@ -1363,6 +1367,12 @@ public class OrderServiceImpl implements OrderService {
|
||||
* @param userId parameter `userId` supplied by the caller
|
||||
*/
|
||||
public void cancelOrder(Long orderId, Long userId) {
|
||||
cancelOrder(orderId, userId, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void cancelOrder(Long orderId, Long userId, String cancelReason) {
|
||||
OrderDO order = orderMapper.selectById(orderId);
|
||||
if (order == null || Integer.valueOf(1).equals(order.getIsDelete())) {
|
||||
/**
|
||||
@@ -1392,6 +1402,8 @@ public class OrderServiceImpl implements OrderService {
|
||||
|
||||
OrderStateMachine.requireAllowedTransition(order.getStatus(), OrderStatus.CANCELLED.getCode());
|
||||
order.setStatus(3);
|
||||
String normalizedReason = StringUtils.hasText(cancelReason) ? cancelReason.trim() : "客户取消预约";
|
||||
order.setCancelReason(normalizedReason.length() > 255 ? normalizedReason.substring(0, 255) : normalizedReason);
|
||||
if (QUOTE_STATUS_CONFIRMING.equals(order.getQuoteStatus())) {
|
||||
order.setQuoteStatus(QUOTE_STATUS_EXPIRED);
|
||||
order.setQuoteUserConfirmed(0);
|
||||
@@ -1400,6 +1412,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
}
|
||||
orderMapper.updateById(order);
|
||||
appointmentCapacityService.releaseByOrder(orderId);
|
||||
enqueueCancellationMessages(orderId);
|
||||
/**
|
||||
* Run business method `restoreUserCoupon`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
@@ -1459,12 +1472,17 @@ public class OrderServiceImpl implements OrderService {
|
||||
throw new RuntimeException("订单状态已变化,请刷新后重试");
|
||||
}
|
||||
order.setStatus(status);
|
||||
if (targetStatus == OrderStatus.CANCELLED && !StringUtils.hasText(order.getCancelReason())) {
|
||||
order.setCancelReason("门店取消预约");
|
||||
}
|
||||
orderMapper.updateById(order);
|
||||
if (targetStatus == OrderStatus.COMPLETED) {
|
||||
businessEventOutboxService.enqueueOrderCompleted(order.getId());
|
||||
}
|
||||
if (targetStatus == OrderStatus.CANCELLED) {
|
||||
appointmentCapacityService.releaseByOrder(order.getId());
|
||||
restoreUserCoupon(order, order.getUserId());
|
||||
enqueueCancellationMessages(order.getId());
|
||||
if (QUOTE_STATUS_CONFIRMING.equals(order.getQuoteStatus())) {
|
||||
order.setQuoteStatus(QUOTE_STATUS_EXPIRED);
|
||||
order.setQuoteUserConfirmed(0);
|
||||
@@ -1475,6 +1493,21 @@ public class OrderServiceImpl implements OrderService {
|
||||
}
|
||||
}
|
||||
|
||||
private void enqueueCancellationMessages(Long orderId) {
|
||||
if (orderId == null) {
|
||||
return;
|
||||
}
|
||||
List<OrderItemDO> items = orderItemMapper.selectByOrderId(orderId);
|
||||
if (items == null) {
|
||||
return;
|
||||
}
|
||||
for (OrderItemDO item : items) {
|
||||
if (item != null && !Integer.valueOf(1).equals(item.getIsDelete())) {
|
||||
wechatSubscribeMessageService.enqueueCancellationNotice(orderId, item.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
/**
|
||||
|
||||
+1
@@ -5,4 +5,5 @@ import lombok.Data;
|
||||
@Data
|
||||
public class PlanningAppointmentStatusDTO {
|
||||
private Integer status;
|
||||
private String cancelReason;
|
||||
}
|
||||
|
||||
+13
@@ -27,6 +27,7 @@ import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.service.AppointmentCapacityService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatSubscribeMessageService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.service.PlanningService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus;
|
||||
@@ -96,6 +97,7 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
private final ShopBusinessExpiryService shopBusinessExpiryService;
|
||||
private final AppointmentCapacityService appointmentCapacityService;
|
||||
private final OrderService orderService;
|
||||
private final WechatSubscribeMessageService wechatSubscribeMessageService;
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
private final ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
|
||||
@@ -248,6 +250,8 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
endTime,
|
||||
trimToNull(dto.getClientRequestId())
|
||||
);
|
||||
wechatSubscribeMessageService.enqueueAppointmentReminder(order.getId(), item.getId());
|
||||
wechatSubscribeMessageService.enqueueServiceStartReminder(order.getId(), item.getId(), startTime);
|
||||
}
|
||||
|
||||
return getAppointment(currentUser, item.getId());
|
||||
@@ -371,6 +375,8 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
item.setArtistId(artist.getId());
|
||||
item.setAppointmentTime(startTime);
|
||||
orderItemMapper.updateById(item);
|
||||
wechatSubscribeMessageService.enqueueAppointmentReminder(order.getId(), item.getId());
|
||||
wechatSubscribeMessageService.enqueueServiceStartReminder(order.getId(), item.getId(), startTime);
|
||||
return getAppointment(currentUser, item.getId());
|
||||
}
|
||||
|
||||
@@ -391,6 +397,13 @@ public class PlanningServiceImpl implements PlanningService {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (targetStatus == OrderStatus.CANCELLED.getCode()) {
|
||||
order.setCancelReason(StringUtils.hasText(dto.getCancelReason()) ? dto.getCancelReason().trim() : "门店取消预约");
|
||||
if (order.getCancelReason().length() > 255) {
|
||||
order.setCancelReason(order.getCancelReason().substring(0, 255));
|
||||
}
|
||||
orderMapper.updateById(order);
|
||||
}
|
||||
orderService.processOrder(orderId, targetStatus);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
SET @column_exists = (
|
||||
SELECT COUNT(1) FROM information_schema.columns
|
||||
WHERE table_schema = DATABASE() AND table_name = 't_order' AND column_name = 'cancel_reason'
|
||||
);
|
||||
SET @migration_sql = IF(
|
||||
@column_exists = 0,
|
||||
'ALTER TABLE t_order ADD COLUMN cancel_reason VARCHAR(255) NULL COMMENT ''预约取消原因'' AFTER customer_remark',
|
||||
'SELECT 1'
|
||||
);
|
||||
PREPARE migration_statement FROM @migration_sql;
|
||||
EXECUTE migration_statement;
|
||||
DEALLOCATE PREPARE migration_statement;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS t_wechat_subscribe_message_log (
|
||||
id BIGINT UNSIGNED NOT NULL COMMENT '订阅消息记录ID',
|
||||
event_key VARCHAR(200) NOT NULL COMMENT '业务事件幂等键',
|
||||
template_code VARCHAR(100) NOT NULL COMMENT '固定微信模板ID',
|
||||
user_id BIGINT UNSIGNED NULL COMMENT '美甲师用户ID',
|
||||
order_id BIGINT UNSIGNED NULL COMMENT '订单ID',
|
||||
order_item_id BIGINT UNSIGNED NULL COMMENT '订单项ID',
|
||||
open_id_hash VARCHAR(128) NULL COMMENT '接收OpenID摘要,不保存明文',
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'PENDING' COMMENT 'PENDING/PROCESSING/RETRY/SENT/FAILED',
|
||||
retry_count INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '重试次数',
|
||||
err_code INT NULL COMMENT '微信错误码',
|
||||
err_msg VARCHAR(500) NULL COMMENT '错误摘要',
|
||||
next_retry_time DATETIME NULL COMMENT '下次处理时间',
|
||||
sent_time DATETIME NULL COMMENT '发送成功时间',
|
||||
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
is_delete TINYINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_wechat_subscribe_event (event_key),
|
||||
KEY idx_wechat_subscribe_due (status, next_retry_time, id),
|
||||
KEY idx_wechat_subscribe_order (order_id, order_item_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='微信小程序订阅消息发送记录';
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
package com.xiaowang.jayucloud.salon.core.modules.integration.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatSubscribeMessageLogDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatSubscribeMessageLogMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class WechatSubscribeMessageServiceImplTest {
|
||||
|
||||
@Mock private WechatSubscribeMessageLogMapper logMapper;
|
||||
@Mock private WechatMiniBindingMapper bindingMapper;
|
||||
@Mock private WechatMiniClientService clientService;
|
||||
@Mock private OrderMapper orderMapper;
|
||||
@Mock private OrderItemMapper orderItemMapper;
|
||||
@Mock private ProductMapper productMapper;
|
||||
@Mock private UserMapper userMapper;
|
||||
@Mock private PhoneCrypto phoneCrypto;
|
||||
|
||||
private WechatMiniProperties properties;
|
||||
private WechatSubscribeMessageServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
properties = new WechatMiniProperties();
|
||||
properties.setSubscribeMessageEnabled(true);
|
||||
properties.setSubscribeMessageProvider("mock");
|
||||
properties.setServiceStartReminderLeadMinutes(30);
|
||||
properties.setSubscribeMessagePage("/pages/appointment-detail/index");
|
||||
properties.setSubscribeMessageMiniprogramState("developer");
|
||||
properties.setSubscribeMessageMaxRetries(3);
|
||||
service = new WechatSubscribeMessageServiceImpl(logMapper, bindingMapper, clientService, properties,
|
||||
orderMapper, orderItemMapper, productMapper, userMapper, phoneCrypto);
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotEnqueueUnassignedAppointment() {
|
||||
OrderItemDO item = new OrderItemDO();
|
||||
item.setId(101L);
|
||||
when(orderItemMapper.selectById(101L)).thenReturn(item);
|
||||
|
||||
service.enqueueAppointmentReminder(1L, 101L);
|
||||
|
||||
verify(logMapper, never()).insert(any(WechatSubscribeMessageLogDO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void enqueueIncludesCurrentArtistInIdempotencyKey() {
|
||||
OrderItemDO item = new OrderItemDO();
|
||||
item.setId(101L);
|
||||
item.setArtistId(7L);
|
||||
when(orderItemMapper.selectById(101L)).thenReturn(item);
|
||||
|
||||
service.enqueueAppointmentReminder(1L, 101L);
|
||||
|
||||
ArgumentCaptor<WechatSubscribeMessageLogDO> captor = ArgumentCaptor.forClass(WechatSubscribeMessageLogDO.class);
|
||||
verify(logMapper).insert(captor.capture());
|
||||
assertEquals("APPOINTMENT:101:7", captor.getValue().getEventKey());
|
||||
assertEquals(7L, captor.getValue().getUserId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendsOnlyCurrentPendingAppointmentToBoundArtist() {
|
||||
LocalDateTime appointmentTime = LocalDateTime.now().plusHours(2);
|
||||
WechatSubscribeMessageLogDO log = new WechatSubscribeMessageLogDO();
|
||||
log.setId(1L);
|
||||
log.setTemplateCode("Dmebp1afiB9U5rw_ASKiMEQWIqYNF8bSM4JPR4PZ5eo");
|
||||
log.setOrderId(11L);
|
||||
log.setOrderItemId(101L);
|
||||
log.setUserId(7L);
|
||||
log.setStatus("PENDING");
|
||||
log.setRetryCount(0);
|
||||
OrderItemDO item = new OrderItemDO();
|
||||
item.setId(101L);
|
||||
item.setOrderId(11L);
|
||||
item.setArtistId(7L);
|
||||
item.setProductId(31L);
|
||||
item.setAppointmentTime(appointmentTime);
|
||||
item.setIsDelete(0);
|
||||
OrderDO order = new OrderDO();
|
||||
order.setId(11L);
|
||||
order.setStatus(OrderStatus.PENDING_SERVICE.getCode());
|
||||
order.setIsDelete(0);
|
||||
order.setCustomerNameSnapshot("小周");
|
||||
UserDO artist = new UserDO();
|
||||
artist.setId(7L);
|
||||
artist.setNickname("小美");
|
||||
WechatMiniBindingDO binding = new WechatMiniBindingDO();
|
||||
binding.setOpenId("openid-value");
|
||||
ProductDO product = new ProductDO();
|
||||
product.setTitle("纯色美甲");
|
||||
when(logMapper.selectDue(any(), any(Integer.class))).thenReturn(List.of(log));
|
||||
when(logMapper.claimForProcessing(1L)).thenReturn(1);
|
||||
when(orderItemMapper.selectById(101L)).thenReturn(item);
|
||||
when(orderMapper.selectById(11L)).thenReturn(order);
|
||||
when(userMapper.selectById(7L)).thenReturn(artist);
|
||||
when(bindingMapper.selectOne(any(Wrapper.class))).thenReturn(binding);
|
||||
when(productMapper.selectById(31L)).thenReturn(product);
|
||||
when(phoneCrypto.index("openid-value")).thenReturn("hash");
|
||||
when(clientService.sendSubscribeMessage(any(), any(), any(), any(), any()))
|
||||
.thenReturn(new WechatMiniClientService.SubscribeMessageResult(true, 0, "ok"));
|
||||
|
||||
service.processDueMessages();
|
||||
|
||||
verify(clientService).sendSubscribeMessage(eq("openid-value"), eq(log.getTemplateCode()),
|
||||
any(), any(), any());
|
||||
assertEquals("hash", log.getOpenIdHash());
|
||||
assertEquals("SENT", log.getStatus());
|
||||
verify(logMapper, times(2)).updateById(log);
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -9,6 +9,7 @@ import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatSubscribeMessageService;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningAppointmentStatusDTO;
|
||||
import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningAppointmentCreateDTO;
|
||||
@@ -61,6 +62,7 @@ class PlanningServiceImplTest {
|
||||
@Mock private ShopBusinessExpiryService shopBusinessExpiryService;
|
||||
@Mock private AppointmentCapacityService appointmentCapacityService;
|
||||
@Mock private OrderService orderService;
|
||||
@Mock private WechatSubscribeMessageService wechatSubscribeMessageService;
|
||||
@Mock private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
@Mock private ObjectStorageUrlSupport objectStorageUrlSupport;
|
||||
|
||||
@@ -70,7 +72,7 @@ class PlanningServiceImplTest {
|
||||
void setUp() {
|
||||
service = new PlanningServiceImpl(adminScopeHelper, userMapper, userService, nailArtistInfoMapper, artistScheduleMapper,
|
||||
artistScheduleExceptionMapper, appointmentReservationMapper, orderMapper, orderItemMapper,
|
||||
productMapper, shopMapper, shopBusinessExpiryService, appointmentCapacityService, orderService, snowflakeIdGenerator,
|
||||
productMapper, shopMapper, shopBusinessExpiryService, appointmentCapacityService, orderService, wechatSubscribeMessageService, snowflakeIdGenerator,
|
||||
objectStorageUrlSupport);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user