接入微信订阅消息并完善预约通知
自动发布开发环境 Nacos 配置 / publish (push) Successful in 20s

This commit is contained in:
2026-11-02 12:11:23 +08:00
parent 3e439543bc
commit 19ca9e2965
29 changed files with 721 additions and 18 deletions
@@ -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;
}
@@ -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;
}
@@ -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);
}
@@ -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.
@@ -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();
}
@@ -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.
@@ -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);
}
}
@@ -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();
}
@@ -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;
@@ -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.
@@ -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
/**
@@ -5,4 +5,5 @@ import lombok.Data;
@Data
public class PlanningAppointmentStatusDTO {
private Integer status;
private String cancelReason;
}
@@ -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='微信小程序订阅消息发送记录';
@@ -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);
}
}
@@ -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);
}
+4 -2
View File
@@ -327,8 +327,10 @@ export const orderApi = {
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
* @param orderId: IdType caller-supplied value for `orderId: IdType`
*/
cancelOrder: (orderId: IdType) => {
return api.put(`/order/cancel/${orderId}`)
cancelOrder: (orderId: IdType, cancelReason?: string) => {
return api.put(`/order/cancel/${orderId}`, undefined, {
params: cancelReason ? { cancelReason } : undefined
})
},
// 后台获取所有订单
@@ -1,8 +1,8 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { computed, h, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { Input, message, Modal } from 'ant-design-vue'
import { afterSaleApi, orderApi } from '../api/order'
import type { AfterSaleVO, OrderArtistChangeRequestVO, OrderArtistReviewVO } from '../api/order'
import { userApi, type ContactInfoVO } from '@/api/user'
@@ -196,11 +196,21 @@ const confirmQuote = () => {
const cancelOrder = () => {
if (!order.value?.id) return
const cancelReason = ref('')
Modal.confirm({
title: '取消订单',
content: '确认取消这笔订单吗?',
content: h('div', [
h('p', { style: 'margin-bottom: 12px' }, '确认取消这笔订单吗?'),
h(Input.TextArea, {
rows: 3,
maxlength: 255,
showCount: true,
placeholder: '可填写取消原因',
'onUpdate:value': (value: string) => { cancelReason.value = value }
})
]),
onOk: async () => {
await runWithGlobalLoading(() => orderApi.cancelOrder(order.value.id as IdType))
await runWithGlobalLoading(() => orderApi.cancelOrder(order.value.id as IdType, cancelReason.value.trim()))
message.success('订单已取消')
await loadOrder()
}
+2 -2
View File
@@ -44,11 +44,11 @@ module.exports = {
})
},
updateStatus(orderId, status) {
updateStatus(orderId, status, cancelReason) {
return request({
url: `/manager/planning/appointments/${orderId}/status`,
method: 'PUT',
data: { status }
data: { status, cancelReason }
})
}
}
@@ -46,7 +46,7 @@ Page({
return
}
try {
await planningApi.updateStatus(this.data.appointment.orderId, status)
await planningApi.updateStatus(this.data.appointment.orderId, status, this._cancelReason || '')
markPlanningRefresh()
wx.showToast({ title: '已更新' })
this.loadDetail()
@@ -65,7 +65,18 @@ Page({
},
cancel() {
this.updateStatus(3)
wx.showModal({
title: '取消预约',
editable: true,
placeholderText: '可填写取消原因',
content: '',
confirmText: '确认取消',
success: result => {
if (!result.confirm) return
this._cancelReason = result.content || ''
this.updateStatus(3)
}
})
},
goTransfer() {
+3
View File
@@ -2,6 +2,7 @@ const authApi = require('../../api/auth')
const auth = require('../../utils/auth')
const { BRAND_CONFIG } = require('../../utils/config')
const loginFlow = require('../../utils/login-flow')
const { requestSubscribeMessages } = require('../../utils/subscribe-message')
function wxLoginCode() {
return new Promise((resolve, reject) => wx.login({
@@ -146,6 +147,8 @@ Page({
async quickLogin() {
if (this.data.loading || !(await this.ensureCanLogin())) return
this._presentedLoginState = ''
// 订阅授权是可选的,拒绝时仍继续登录;调用必须发生在用户点击登录链路中。
await requestSubscribeMessages()
const rememberMe = await this.chooseRememberMode()
if (rememberMe === null) return
this.setData({ rememberMe, loading: true })
+7 -4
View File
@@ -835,18 +835,21 @@ Page({
if (!appointment) return
wx.showModal({
title: '取消预约',
content: '确定取消这条预约吗?',
editable: true,
placeholderText: '可填写取消原因',
content: '',
confirmText: '确认取消',
success: result => {
if (result.confirm) {
this.updateAppointmentStatus(appointment.orderId, 3)
this.updateAppointmentStatus(appointment.orderId, 3, result.content || '')
}
}
})
},
async updateAppointmentStatus(orderId, status) {
async updateAppointmentStatus(orderId, status, cancelReason) {
try {
await planningApi.updateStatus(orderId, status)
await planningApi.updateStatus(orderId, status, cancelReason)
wx.showToast({ title: '预约已取消', icon: 'success' })
this.loadCalendar()
} catch (error) {
@@ -0,0 +1,21 @@
const TEMPLATE_IDS = [
'jURyVPL52qyUhm_c_OyvED5zivUZr_3LfAXjfV-KOJc',
'0v80O2xaOS8D_aSrurqTo4fds8FmyMlEOsy66LXsjNQ',
'Dmebp1afiB9U5rw_ASKiMEQWIqYNF8bSM4JPR4PZ5eo'
]
function requestSubscribeMessages() {
return new Promise(resolve => {
if (!wx.requestSubscribeMessage) {
resolve({})
return
}
wx.requestSubscribeMessage({
tmplIds: TEMPLATE_IDS,
success: resolve,
fail: () => resolve({})
})
})
}
module.exports = { TEMPLATE_IDS, requestSubscribeMessages }
@@ -0,0 +1,32 @@
const assert = require('assert')
let requestOptions
global.wx = {
requestSubscribeMessage(options) {
requestOptions = options
options.success({
[options.tmplIds[0]]: 'accept',
[options.tmplIds[1]]: 'reject',
[options.tmplIds[2]]: 'accept'
})
}
}
const { TEMPLATE_IDS, requestSubscribeMessages } = require('./subscribe-message')
async function run() {
const result = await requestSubscribeMessages()
assert.deepStrictEqual(requestOptions.tmplIds, TEMPLATE_IDS)
assert.strictEqual(TEMPLATE_IDS.length, 3)
assert.strictEqual(result[TEMPLATE_IDS[0]], 'accept')
assert.strictEqual(result[TEMPLATE_IDS[1]], 'reject')
assert.strictEqual(result[TEMPLATE_IDS[2]], 'accept')
global.wx.requestSubscribeMessage = options => options.fail(new Error('user cancelled'))
assert.deepStrictEqual(await requestSubscribeMessages(), {})
}
run().catch(error => {
console.error(error)
process.exitCode = 1
})
@@ -0,0 +1,55 @@
# Salon 微信订阅消息配置说明
更新时间:2026-11-02
## 1. 固定模板
模板由微信小程序后台维护,代码只使用以下模板,不支持在 Nacos 或后台编辑模板 ID、字段名、字段类型和正文:
| 场景 | 模板 ID | 发送对象 |
| --- | --- | --- |
| 服务开始提醒 | `jURyVPL52qyUhm_c_OyvED5zivUZr_3LfAXjfV-KOJc` | 当前承接预约的美甲师 |
| 预约取消通知 | `0v80O2xaOS8D_aSrurqTo4fds8FmyMlEOsy66LXsjNQ` | 当前承接预约的美甲师 |
| 预约提醒 | `Dmebp1afiB9U5rw_ASKiMEQWIqYNF8bSM4JPR4PZ5eo` | 当前承接预约的美甲师 |
未分配美甲师的预约不发送订阅消息。
## 2. 字段映射
- 服务开始提醒:`thing1` 固定为“预约即将开始,请提前准备”;`date3` 为开始日期;`thing6` 为服务项目;`thing7` 为客户姓名。
- 预约取消通知:`name1` 为客户姓名;`thing2` 为原预约项目;`time4` 为原预约时间;`thing6` 为取消原因。
- 预约提醒:`thing1` 为预约项目;`time2` 为预约时间;`thing3` 为注意事项兜底文案;`name5` 为预约技师;`name6` 为预约客户。
字段长度由服务端按微信模板限制裁剪。`date3` 日期字段使用 `yyyy年MM月dd日`,`time2/time4` 时间字段使用 `HH:mm`;服务开始提醒的“提前 30 分钟”由服务端定时触发,模板原生日期字段不扩展为自定义时间字段。
## 3. 环境配置
配置位于各环境 Salon Core 的 `core.yaml`:
| 配置 | DEV | SIT/PROD |
| --- | --- | --- |
| `subscribe-message-enabled` | `true` | `true` |
| `subscribe-message-provider` | `mock` | `wechat` |
| `service-start-reminder-lead-minutes` | `30` | `30` |
| `subscribe-message-page` | `/pages/appointment-detail/index` | `/pages/appointment-detail/index` |
| `subscribe-message-miniprogram-state` | `developer` | SIT 使用 `trial`,PROD 使用 `formal` |
| `subscribe-message-max-retries` | `3` | `3` |
小程序登录在用户已经同意协议后请求三个模板的订阅授权。用户全部或部分拒绝都不影响登录、预约和取消;后端按微信实际返回结果记录发送成功、拒绝、模板失效、重试和最终失败。
## 4. 发送与幂等
- 新建已分配预约、首次分配和改派后生成预约提醒及服务开始提醒。
- 取消预约生成取消通知;取消原因为空时使用“门店取消预约”或“客户取消预约”。
- 定时任务扫描服务开始提醒,按预约时间提前 30 分钟处理,重复扫描不会重复发送。
- 日志保存模板、业务事件、预约项、美甲师、状态和错误摘要;OpenID 不写入日志,数据库只保存摘要。
- 改派或取消后,处理器重新校验预约状态和当前美甲师,旧任务不会误发。
## 5. 微信后台上线前检查
1. 当前小程序已添加并启用上表三个模板。
2. 各环境 AppID/AppSecret 与实际小程序环境一致,敏感值仅通过受控 Nacos 配置提供。
3. `subscribe-message-page` 对应页面在体验版和正式版均可访问。
4. SIT 使用真实测试账号验证预约、取消和服务开始三种消息;自动化测试只使用 DEV Mock,不消耗真实订阅额度。
本说明不包含 AppSecret、access_token、完整 OpenID 或其他密钥。
@@ -93,6 +93,7 @@ MessageHub 的地址、交换机、路由和来源系统放在对应环境 `core
- Flyway V8 增加客户联系方式组合去重和美甲师专属颜色;V9 增加美甲师注册申请与门店员工档案的预关联字段,以及待审核目标员工唯一索引。V9 审核通过时将申请人的微信身份转移到已选员工档案,未关联员工不允许通过手机号登录;头像经注册票据受限上传并通过内容审核后才展示。两个迁移均为向前兼容版本 SQL,不修改初始化 SQL。
- Flyway V10 增加门店预约运营营业时间和默认预约时长字段;老门店时长初始化为60分钟,迁移可重复执行,不修改冻结初始化 SQL。店长通过独立预约运营设置接口保存营业时间和时长,不触发门店公开资料审核;门店名称仍通过内容审核流程提交。普通预约时长优先使用明确选择值、再使用款式时长、最后使用门店默认值;历史日期和已过时间由小程序与 Core 双重拒绝,需转历史补单。
- 预约选择客户使用门店范围专用接口返回完整联系电话,普通客户列表仍脱敏;客户预约建档与客户页保持姓名/微信号/手机号三字段完全一致才判重。预约日历以门店运营营业时间生成可选时段;接口无有效营业时间时不生成默认时段,页面明确提示先到店铺设置完成配置。
- 微信订阅消息使用三个固定小程序模板:新建/分配预约发送“预约提醒”,取消发送“预约取消通知”,开始前30分钟发送“服务开始提醒”;只通知当前承接美甲师,未分配不发送。DEV 使用 Mock,SIT/PROD 使用微信 Provider;用户拒绝订阅不影响登录或预约。配置、字段映射和上线检查见 `docs/scripts/Salon微信订阅消息配置说明_20261102.md`,数据库发送日志由 V12 迁移创建。
## 8. 操作前检查
@@ -42,6 +42,12 @@ jayucloud-salon:
mini:
app-id: wxb6d77f7c07020d51
app-secret: "e277fa749a779547dab6086f56c2e833"
subscribe-message-enabled: true
subscribe-message-provider: mock
service-start-reminder-lead-minutes: 30
subscribe-message-page: /pages/appointment-detail/index
subscribe-message-miniprogram-state: developer
subscribe-message-max-retries: 3
brand:
message-template-name: JayuCloud-Salon
manager-register-shop-description: 甲屿店务注册店铺
@@ -41,6 +41,12 @@ jayucloud-salon:
mini:
app-id: wxb6d77f7c07020d51
app-secret: ""
subscribe-message-enabled: true
subscribe-message-provider: wechat
service-start-reminder-lead-minutes: 30
subscribe-message-page: /pages/appointment-detail/index
subscribe-message-miniprogram-state: formal
subscribe-message-max-retries: 3
brand:
message-template-name: JayuCloud-Salon
manager-register-shop-description: 甲屿店务注册店铺
@@ -41,6 +41,12 @@ jayucloud-salon:
mini:
app-id: wxb6d77f7c07020d51
app-secret: "e277fa749a779547dab6086f56c2e833"
subscribe-message-enabled: true
subscribe-message-provider: wechat
service-start-reminder-lead-minutes: 30
subscribe-message-page: /pages/appointment-detail/index
subscribe-message-miniprogram-state: trial
subscribe-message-max-retries: 3
brand:
message-template-name: JayuCloud-Salon
manager-register-shop-description: 甲屿店务注册店铺