200 changed files with 5149 additions and 13642 deletions
+1 -14
View File
@@ -99,20 +99,7 @@
"Bash(python -c \"print\\('hello'\\)\")", "Bash(python -c \"print\\('hello'\\)\")",
"Bash(grep -r \"RightPanel\" src/pages/client/index.tsx)", "Bash(grep -r \"RightPanel\" src/pages/client/index.tsx)",
"Bash(grep \"statusBar\\\\|statusDot\" src/pages/client/index.tsx)", "Bash(grep \"statusBar\\\\|statusDot\" src/pages/client/index.tsx)",
"Bash(grep \"routeActions\\\\|routeActionsTitle\" src/pages/client/components/CenterView/index.tsx)", "Bash(grep \"routeActions\\\\|routeActionsTitle\" src/pages/client/components/CenterView/index.tsx)"
"Read(//c/Users/10989/.m2/repository/com/alipay/**)",
"Bash(\"/e/java/apache-maven-3.9.11-bin/apache-maven-3.9.11/bin/mvn.cmd\" -q -o -pl . compile)",
"Bash(\"/e/java/apache-maven-3.9.11-bin/apache-maven-3.9.11/bin/mvn.cmd\" -q -pl zlt-commons/zlt-alipay-spring-boot-starter -am compile -DskipTests)",
"Bash(grep -rn \"alipay\" zlt-business/order-center/src/main/resources/sql/)",
"Bash(ls zlt-business/order-center/src/main/resources/sql/)",
"WebFetch(domain:opendocs.alipay.com)",
"Bash(mvn -v)",
"WebFetch(domain:mvnrepository.com)",
"WebFetch(domain:raw.githubusercontent.com)",
"Bash(xargs -I{} jar tf {})",
"Bash(locate alipay-sdk-java *)",
"Bash(jar tf *)",
"Bash(javap *)"
], ],
"deny": [], "deny": [],
"ask": [] "ask": []
+1 -4
View File
@@ -11,16 +11,13 @@ nacos/
.claude/agents/ .claude/agents/
.claude/team-collaboration-matrix.md .claude/team-collaboration-matrix.md
.reasonix
reasonix.toml
# Cesium static assets (auto-generated by npm install) # Cesium static assets (auto-generated by npm install)
zlt-web/react-web-next/public/cesium/ zlt-web/react-web-next/public/cesium/
zlt-web/yingyan/public/cesium/ zlt-web/yingyan/public/cesium/
# 忽略 dist.zip 文件
zlt-web/react-web-next/dist.zip zlt-web/react-web-next/dist.zip
zlt-web/yingyan/dist.zip zlt-web/yingyan/dist.zip
-7
View File
@@ -1,7 +0,0 @@
{
"permissions": {
"allow": [
"Agent(Explore)"
]
}
}
@@ -1,58 +0,0 @@
<h2>哪种指点飞行操作流更顺手?</h2>
<p class="subtitle">重点比较:从开始飞行到连续改点,需要多少次中断和确认。</p>
<div class="cards" style="grid-template-columns: repeat(3, minmax(0, 1fr));">
<div class="card" data-choice="a" onclick="toggleSelect(this)">
<div class="card-image" style="padding:16px;background:#122033;min-height:280px;color:#d9e8f5;">
<div style="font-size:12px;color:#7f9bb5;margin-bottom:10px;">现有流程</div>
<div style="background:#223754;padding:12px;border-radius:4px;margin:8px 0;">右侧面板<br><b>指点飞行</b></div>
<div style="text-align:center;color:#65b8ff;">↓ 确认开始</div>
<div style="background:#223754;padding:12px;border-radius:4px;margin:8px 0;">等待升空</div>
<div style="text-align:center;color:#65b8ff;">↓ 点击地图</div>
<div style="background:#f5f7fb;color:#14253b;padding:12px;border-radius:4px;margin:8px 0;">目标确认弹窗<br><small>高度、速度、确认</small></div>
<div style="text-align:center;color:#65b8ff;">↓ 到达后才能再选点</div>
<div style="background:#223754;padding:12px;border-radius:4px;margin:8px 0;">重复上述步骤</div>
</div>
<div class="card-body"><h3>A. 分步确认</h3><p>控制感强,但连续指点时被弹窗和状态等待反复打断。</p></div>
</div>
<div class="card" data-choice="b" onclick="toggleSelect(this)" style="border-color:#1f8fff;">
<div class="card-image" style="padding:16px;background:#10273a;min-height:280px;color:#d9e8f5;position:relative;">
<div style="font-size:12px;color:#7fcaef;margin-bottom:10px;">推荐:地图优先</div>
<div style="height:140px;border:1px solid #39769b;background:linear-gradient(135deg,#173c55,#1d5870);position:relative;border-radius:3px;">
<div style="position:absolute;left:42%;top:38%;font-size:32px;color:#ffcf5c;">✦</div>
<div style="position:absolute;right:10px;top:8px;background:#0b1925cc;padding:6px 8px;font-size:12px;">正在指点 · 5 m/s</div>
<div style="position:absolute;left:15%;bottom:15%;color:#7ad5ff;font-size:22px;">✈</div>
</div>
<div style="margin-top:10px;background:#0b1925;padding:10px;border-left:3px solid #1f9fff;display:flex;justify-content:space-between;align-items:center;">
<span><b>新目标</b><br><small>113.123456, 23.123456</small></span>
<span style="color:#ffcf5c;">发送</span>
</div>
<div style="font-size:12px;color:#9bb8c9;margin-top:10px;line-height:1.5;">首次进入模式后,地图点击直接更新目标。高度和速度沿用上次值,可在紧凑工具条修改;短暂显示“撤销”而不是每次弹窗。</div>
</div>
<div class="card-body"><h3>B. 地图优先</h3><p>一次启用,连续点击连续改点。危险操作才二次确认,常规改点不打断地图。</p></div>
</div>
<div class="card" data-choice="c" onclick="toggleSelect(this)">
<div class="card-image" style="padding:16px;background:#17242b;min-height:280px;color:#d9e8f5;">
<div style="font-size:12px;color:#a9c4b8;margin-bottom:10px;">精细作业模式</div>
<div style="height:92px;border:1px solid #607d70;background:#283b35;border-radius:3px;position:relative;">
<span style="position:absolute;left:25%;top:22%;font-size:22px;color:#f2d477;">①</span>
<span style="position:absolute;left:58%;top:50%;font-size:22px;color:#f2d477;">②</span>
<span style="position:absolute;left:12%;bottom:10%;color:#79c9ee;">✈</span>
</div>
<div style="margin-top:10px;background:#24332e;padding:10px;border-radius:3px;">
<b>下一目标</b><span style="float:right;color:#f2d477;">②</span><br>
<small>113.123456, 23.123456 · 120m</small>
</div>
<div style="display:flex;gap:6px;margin-top:8px;"><span style="background:#31463e;padding:5px 7px;font-size:12px;">添加目标</span><span style="background:#31463e;padding:5px 7px;font-size:12px;">确认发送</span></div>
<div style="font-size:12px;color:#a9c4b8;margin-top:10px;line-height:1.5;">地图点击先加入临时队列,用户可以复核、排序或删除后发送。</div>
</div>
<div class="card-body"><h3>C. 目标队列</h3><p>适合测绘和有规划的巡查,但增加了一层操作,与即时指点的感觉相反。</p></div>
</div>
</div>
<div class="section" style="margin-top:24px;">
<p class="label">选择建议</p>
<p>我建议选 <b>B</b>:首次启用和结束返航保留明确确认;飞行期间把地图点击变成主操作,避免“点一下、弹一次、等一次”。</p>
</div>
@@ -1,38 +0,0 @@
<h2>点击建筑时,目标高度应该怎么计算?</h2>
<p class="subtitle">现有代码把“模型命中高度 + 输入高度”直接下发;它不等于界面所说的“相对地面高度”。</p>
<div class="split">
<div class="mockup" data-choice="surface" onclick="toggleSelect(this)">
<div class="mockup-header">现有:相对点击表面</div>
<div class="mockup-body" style="background:#132633;min-height:300px;position:relative;overflow:hidden;color:#e9f5fa;">
<div style="position:absolute;left:12%;bottom:8%;width:78%;height:3px;background:#5e856a;"></div>
<div style="position:absolute;left:52%;bottom:9%;width:22%;height:44%;background:#73808b;border:2px solid #aebac0;"><span style="position:absolute;top:8px;left:12px;font-size:12px;">楼</span></div>
<div style="position:absolute;left:22%;bottom:12%;font-size:28px;">✈</div>
<div style="position:absolute;left:63%;bottom:59%;font-size:26px;color:#ffca60;">✦</div>
<div style="position:absolute;left:58%;bottom:72%;border-top:1px dashed #ffca60;width:10%;"></div>
<div style="position:absolute;right:8%;top:9%;font-size:12px;background:#202f3b;padding:8px;line-height:1.5;">模型表面 40m<br>输入“120m”<br><b style="color:#ffca60;">目标 = 160m</b></div>
<div style="position:absolute;left:7%;top:8%;font-size:12px;color:#ff9c9c;">问题:界面称“相对地面”,实际相对楼顶/立面;路径中的更高障碍也没有检查。</div>
</div>
<div style="padding:12px;"><b>方案 A:保留现状</b><br><small>实现最少,但语义误导,无法保证航线净空。</small></div>
</div>
<div class="mockup" data-choice="safe-corridor" onclick="toggleSelect(this)" style="border-color:#1f8fff;">
<div class="mockup-header">推荐:安全航高 + 净空保护</div>
<div class="mockup-body" style="background:#132633;min-height:300px;position:relative;overflow:hidden;color:#e9f5fa;">
<div style="position:absolute;left:12%;bottom:8%;width:78%;height:3px;background:#5e856a;"></div>
<div style="position:absolute;left:52%;bottom:9%;width:22%;height:44%;background:#73808b;border:2px solid #aebac0;"><span style="position:absolute;top:8px;left:12px;font-size:12px;">楼</span></div>
<div style="position:absolute;left:22%;bottom:12%;font-size:28px;">✈</div>
<div style="position:absolute;left:63%;bottom:77%;font-size:26px;color:#75e5ff;">✦</div>
<div style="position:absolute;left:26%;bottom:80%;width:42%;border-top:3px solid #4fc3f7;"></div>
<div style="position:absolute;left:25%;bottom:74%;font-size:12px;color:#75e5ff;">安全飞行走廊:障碍物顶部 + 安全净空</div>
<div style="position:absolute;right:7%;top:8%;font-size:12px;background:#163c4d;padding:8px;line-height:1.5;">地图点击只取经纬度<br>计划高度 = max:<br>· 当前安全航高<br>· 目标建筑顶部 + 净空<br>· 路径障碍顶部 + 净空</div>
<div style="position:absolute;left:7%;top:8%;font-size:12px;color:#b8e8c5;">高度策略明确;无法可靠评估净空时,拒绝下发而不是猜测。</div>
</div>
<div style="padding:12px;"><b>方案 B:安全走廊(推荐)</b><br><small>点击只决定水平位置;系统决定或校验实际椭球目标高。</small></div>
</div>
</div>
<div class="section" style="margin-top:22px;">
<p class="label">建议交互</p>
<p>把“飞行高度”改成“安全航高(相对起飞点)”,默认继承当前安全高度。点击楼顶时显示“目标位于建筑上方,系统已抬升至安全高度”;若无法验证模型/地形净空,则显示风险并禁止确认飞行。</p>
</div>
@@ -1,3 +0,0 @@
<div style="display:flex;align-items:center;justify-content:center;min-height:60vh">
<p class="subtitle">继续在终端确认安全策略...</p>
</div>
@@ -1,3 +0,0 @@
<div style="display:flex;align-items:center;justify-content:center;min-height:60vh">
<p class="subtitle">正在整理“预览后发送 + 安全航高”的交互方案...</p>
</div>
@@ -1 +0,0 @@
{"reason":"idle timeout","timestamp":1784875445807}
@@ -1 +0,0 @@
628
@@ -1,28 +0,0 @@
# 指点飞行交互与安全实现计划
## 目标
将指点飞行改为“点击产生候选点,明确发送后才改飞”的交互;防止把建筑或模型表面的命中高度直接作为飞行目标高度;记录每一次下发及风险确认。
## 第一版边界
- 点击模型表面仅作为目标位置与障碍物候选高度。
- 目标椭球高度取当前无人机椭球高度与候选表面高度加净空的较大值。
- 第一版不宣称已完成路径三维净空验证;路径未验证时必须由当前账户确认风险后才可发送。
- 后端保存首次 `fly_to_point` 与后续 `fly_to_point_update` 的下发记录和风险审计信息。
## 实施步骤
1. 先为后端安全命令对象编写单元测试,覆盖“未验证净空必须确认风险”与“已验证净空不要求确认”两种行为。
2. 新增安全命令对象、目标下发请求对象和 `mission_fly_to_point` 实体/Mapper;迁移脚本补充审计字段与唯一序号约束。
3. 将任务更新接口改为强类型请求,后端从登录上下文取得确认人;对未验证风险但未确认的请求拒绝下发。
4. 调整任务服务:根据目标历史决定首次命令或更新命令,设备命令成功后记录历史与最新任务目标;结束时先停止指点会话,再调用真实返航接口。
5. 前端 Hook 分离候选目标和已发送目标;候选目标不会改变当前飞行目标,发送成功后才成为已发送目标。
6. 前端 Cesium 点选在起飞、等待和飞行中均可用,候选点与已发送点使用不同标识;点选高度只用于净空计算和风险提示。
7. 用紧凑浮层替代每次点选的大弹窗,提供发送、丢弃和风险确认;保留起飞、结束飞行的明确确认。
## 验证
- 后端:`mvn -pl zlt-business/order-center -am -Dtest=FlyToPointTargetCommandTest -Dsurefire.failIfNoSpecifiedTests=false test`
- 前端:`npm run tsc`,随后执行 `npm run build`。
- 人工:起飞后点 A 仅预览;发送 A 后飞行;飞往 A 时点 B 仅预览;发送 B 后才改飞;未勾选风险确认不可发送。
@@ -104,20 +104,5 @@ public class CtripDistributorConfig {
* 沙箱测试-人工出票/退订确认/凭证变更接口icode * 沙箱测试-人工出票/退订确认/凭证变更接口icode
*/ */
private String simulateConfirm; private String simulateConfirm;
/**
* 产品列表接口icode
*/
private String productList;
/**
* 位置列表接口icode
*/
private String locationList;
/**
* 产品全量列表接口icode
*/
private String allProducts;
} }
} }
@@ -4,18 +4,9 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.coupon.entity.CtripContact;
import com.central.coupon.entity.CtripDistOrder; import com.central.coupon.entity.CtripDistOrder;
import com.central.coupon.entity.CtripOrder;
import com.central.coupon.entity.CtripOrderItem;
import com.central.coupon.mapper.CtripContactMapper;
import com.central.coupon.mapper.CtripDistOrderMapper; import com.central.coupon.mapper.CtripDistOrderMapper;
import com.central.coupon.mapper.CtripOrderItemMapper;
import com.central.coupon.mapper.CtripOrderMapper;
import com.central.coupon.model.CtripConsumedNoticeResponse;
import com.central.coupon.service.CtripConsumedService;
import com.central.coupon.service.ICtripDistOrderService; import com.central.coupon.service.ICtripDistOrderService;
import com.central.coupon.service.IOrderDetailService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
@@ -24,13 +15,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
@Slf4j @Slf4j
@RestController @RestController
@@ -44,21 +30,6 @@ public class CtripDistOrderController {
@Autowired @Autowired
private CtripDistOrderMapper ctripDistOrderMapper; private CtripDistOrderMapper ctripDistOrderMapper;
@Autowired
private CtripContactMapper ctripContactMapper;
@Autowired
private CtripOrderMapper ctripOrderMapper;
@Autowired
private CtripOrderItemMapper ctripOrderItemMapper;
@Autowired
private CtripConsumedService ctripConsumedService;
@Autowired
private IOrderDetailService orderDetailService;
/** /**
* 分页查询携程分销订单列表 * 分页查询携程分销订单列表
*/ */
@@ -126,15 +97,6 @@ public class CtripDistOrderController {
Long ctripProductId = Long.valueOf(params.get("ctripProductId").toString()); Long ctripProductId = Long.valueOf(params.get("ctripProductId").toString());
String tenantId = (String) params.get("tenantId"); String tenantId = (String) params.get("tenantId");
String mobile = params.get("mobile") != null ? params.get("mobile").toString() : null; String mobile = params.get("mobile") != null ? params.get("mobile").toString() : null;
if (mobile == null || mobile.isEmpty()) {
String[] prefixes = {"130","131","132","133","134","135","136","137","138","139",
"150","151","152","153","155","156","157","158","159",
"170","171","172","173","175","176","177","178",
"180","181","182","183","184","185","186","187","188","189",
"191","193","195","196","197","198","199"};
String prefix = prefixes[ThreadLocalRandom.current().nextInt(prefixes.length)];
mobile = prefix + String.format("%08d", ThreadLocalRandom.current().nextInt(100000000));
}
try { try {
ctripDistOrderService.createCtripDistOrder(orderNo, orderAmount, ctripProductId, tenantId, mobile); ctripDistOrderService.createCtripDistOrder(orderNo, orderAmount, ctripProductId, tenantId, mobile);
@@ -163,131 +125,4 @@ public class CtripDistOrderController {
public Result<CtripDistOrder> getCtripDistOrder(@PathVariable String orderNo) { public Result<CtripDistOrder> getCtripDistOrder(@PathVariable String orderNo) {
return Result.succeed(ctripDistOrderService.getByOrderNo(orderNo)); return Result.succeed(ctripDistOrderService.getByOrderNo(orderNo));
} }
/**
* 手动核销携程分销订单
*/
@Operation(summary = "手动核销携程分销订单")
@PostMapping("/consume/{ctripOrderId}")
public Result<String> consumeCtripDistOrder(
@Parameter(description = "携程订单ID") @PathVariable Long ctripOrderId) {
log.info("手动核销携程分销订单,ctripOrderId: {}", ctripOrderId);
try {
// 1. 查找CtripDistOrder
LambdaQueryWrapper<CtripDistOrder> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(CtripDistOrder::getCtripOrderId, ctripOrderId)
.eq(CtripDistOrder::getDeleted, 0);
CtripDistOrder distOrder = ctripDistOrderMapper.selectOne(queryWrapper);
if (distOrder == null) {
return Result.failed("未找到携程分销订单,ctripOrderId: " + ctripOrderId);
}
if (distOrder.getConsumeStatus() != null && distOrder.getConsumeStatus() == 1) {
return Result.failed("该订单已核销,无需重复核销");
}
// 2. 获取手机号,根据手机号通过联系人表查找CtripOrder
String mobile = distOrder.getMobile();
if (mobile == null || mobile.isEmpty()) {
return Result.failed("分销订单手机号为空,无法核销");
}
List<CtripContact> contacts = ctripContactMapper.selectByMobile(mobile);
if (contacts == null || contacts.isEmpty()) {
distOrder.setConsumeStatus(2);
distOrder.setErrorMsg("未找到手机号对应的携程联系人记录");
ctripDistOrderMapper.updateById(distOrder);
return Result.failed("未找到手机号对应的携程联系人记录");
}
List<Long> orderIds = contacts.stream()
.map(CtripContact::getOrderId)
.distinct()
.collect(Collectors.toList());
// 筛选状态为PAYMENT_CONFIRMED(13)的订单
List<CtripOrder> confirmedOrders = new ArrayList<>();
for (Long orderId : orderIds) {
CtripOrder ctripOrder = ctripOrderMapper.selectById(orderId);
if (ctripOrder != null && Integer.valueOf(13).equals(ctripOrder.getStatus())) {
confirmedOrders.add(ctripOrder);
}
}
if (confirmedOrders.isEmpty()) {
distOrder.setConsumeStatus(2);
distOrder.setErrorMsg("未找到状态为PAYMENT_CONFIRMED的携程订单");
ctripDistOrderMapper.updateById(distOrder);
return Result.failed("未找到状态为PAYMENT_CONFIRMED的携程订单");
}
// 3. 对每个符合条件的CtripOrder执行核销
boolean anySuccess = false;
StringBuilder errorMsgs = new StringBuilder();
for (CtripOrder ctripOrder : confirmedOrders) {
try {
// 建立订单关联关系
if (ctripOrder.getOrderNo() == null || ctripOrder.getOrderNo().trim().isEmpty()) {
ctripOrder.setOrderNo(distOrder.getOrderNo());
ctripOrderMapper.updateById(ctripOrder);
}
if (!orderDetailService.validateOrderForConsume(ctripOrder.getOtaOrderId())) {
continue;
}
List<CtripOrderItem> orderItems = ctripOrderItemMapper.selectByOrderId(ctripOrder.getId());
if (orderItems == null || orderItems.isEmpty()) {
continue;
}
for (CtripOrderItem item : orderItems) {
if (item.getQuantity() == null || item.getQuantity() <= 0) {
continue;
}
CtripConsumedController.CtripConsumeRequest request = new CtripConsumedController.CtripConsumeRequest();
request.setOtaOrderId(ctripOrder.getOtaOrderId());
request.setSupplierOrderId(ctripOrder.getSupplierOrderId());
request.setItemId(item.getItemId());
request.setUseQuantity(item.getQuantity());
request.setRemark("手动核销分销订单,orderNo: " + distOrder.getOrderNo());
CtripConsumedNoticeResponse response = ctripConsumedService.consumeOrder(request);
boolean success = response != null && "0000".equals(response.getHeader().getResultCode());
if (success) {
anySuccess = true;
} else {
String errMsg = response != null ? response.getHeader().getResultMessage() : "未知错误";
errorMsgs.append("otaOrderId=").append(ctripOrder.getOtaOrderId())
.append(",itemId=").append(item.getItemId())
.append(":").append(errMsg).append("; ");
}
}
} catch (Exception e) {
errorMsgs.append("otaOrderId=").append(ctripOrder.getOtaOrderId())
.append(":").append(e.getMessage()).append("; ");
}
}
// 4. 更新CtripDistOrder状态
if (anySuccess) {
distOrder.setConsumeStatus(1);
distOrder.setConsumeTime(LocalDateTime.now());
distOrder.setCtripOrderStatus("CONSUMED");
distOrder.setErrorMsg(errorMsgs.length() > 0 ? "部分核销异常: " + errorMsgs : null);
ctripDistOrderMapper.updateById(distOrder);
return Result.succeed("核销成功");
} else {
distOrder.setConsumeStatus(2);
distOrder.setErrorMsg(errorMsgs.length() > 0 ? errorMsgs.toString() : "所有订单核销均失败");
ctripDistOrderMapper.updateById(distOrder);
return Result.failed("核销失败: " + distOrder.getErrorMsg());
}
} catch (Exception e) {
log.error("手动核销携程分销订单异常,ctripOrderId: {}", ctripOrderId, e);
return Result.failed("核销异常: " + e.getMessage());
}
}
} }
@@ -82,7 +82,6 @@ public class CtripDistTestController {
icode.put("cancelVerify", ctripDistributorConfig.getIcode().getCancelVerify()); icode.put("cancelVerify", ctripDistributorConfig.getIcode().getCancelVerify());
icode.put("cancel", ctripDistributorConfig.getIcode().getCancel()); icode.put("cancel", ctripDistributorConfig.getIcode().getCancel());
icode.put("bookingDetail", ctripDistributorConfig.getIcode().getBookingDetail()); icode.put("bookingDetail", ctripDistributorConfig.getIcode().getBookingDetail());
icode.put("allProducts",ctripDistributorConfig.getIcode().getAllProducts());
data.put("icode", icode); data.put("icode", icode);
} else { } else {
data.put("icode", "null - icode未配置!"); data.put("icode", "null - icode未配置!");
@@ -132,7 +131,7 @@ public class CtripDistTestController {
try { try {
Map<String, Object> result = ctripDistApiService.getProductDetail(productId); Map<String, Object> result = ctripDistApiService.getProductDetail(productId);
log.info("产品详情返回: {}", result); log.info("产品详情返回: {}", result);
return Result.succeed(result, "获取产品详情成功"); return Result.succeed(result, "获取产���详情成功");
} catch (Exception e) { } catch (Exception e) {
log.error("获取产品详情失败,productId: {}", productId, e); log.error("获取产品详情失败,productId: {}", productId, e);
return Result.failed("获取产品详情失败: " + e.getMessage()); return Result.failed("获取产品详情失败: " + e.getMessage());
@@ -205,7 +204,7 @@ public class CtripDistTestController {
* *
* 调用示例:POST /ctrip/dist/test/check-availability * 调用示例:POST /ctrip/dist/test/check-availability
* *
* 产品2示例(如果模板里是 P_NAME,最终会按 P_CNAME 下发,2出行人): * 产品2示例(中文姓名+身份证,2出行人):
* { * {
* "productId": xxx, * "productId": xxx,
* "packageId": xxx, * "packageId": xxx,
@@ -218,7 +217,7 @@ public class CtripDistTestController {
* ] * ]
* } * }
* *
* 产品3示例(姓名字段会优先匹配中文姓名题;若模板为 P_NAME,也会改成 P_CNAME): * 产品3示例(英文姓名,quantity=2但只需1个出行人):
* { * {
* "productId": 39098283, * "productId": 39098283,
* "packageId": xxx, * "packageId": xxx,
@@ -226,7 +225,7 @@ public class CtripDistTestController {
* "price": 68.00, * "price": 68.00,
* "quantity": 2, * "quantity": 2,
* "passengers": [ * "passengers": [
* {"name": "张三"} * {"P_FIRSTCNAME": "Chao", "P_LASTCNAME": "Du"}
* ] * ]
* } * }
*/ */
@@ -537,145 +536,6 @@ public class CtripDistTestController {
} }
} }
// ==================== 9. 获取位置列表 ====================
/**
* 获取位置列表
* 用途:查询可用城市/地区列表,获取locationID和locationType供产品列表接口使用
* locale固定为zh-CN
*
* 调用示例:GET /ctrip/dist/test/location-list?pageIndex=1&pageSize=20
*/
@GetMapping("/location-list")
@Operation(summary = "9.获取位置列表")
public Result<Map<String, Object>> testLocationList(
@RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "20") int pageSize) {
log.info("===== 获取位置列表,pageIndex: {}, pageSize: {} =====", pageIndex, pageSize);
try {
Map<String, Object> result = ctripDistApiService.getLocationList(pageIndex, pageSize);
log.info("位置列表返回: {}", result);
return Result.succeed(result, "获取位置列表成功");
} catch (Exception e) {
log.error("获取位置列表失败", e);
return Result.failed("获取位置列表失败: " + e.getMessage());
}
}
// ==================== 10. 获取产品列表 ====================
/**
* 获取产品列表
* 用途:查询产品列表,site和destination的locationID/locationType自动从位置列表接口获取
* 可通过locationIndex指定使用位置列表中的第几个位置(0-based,默认0)
*
* 调用示例:POST /ctrip/dist/test/product-list
* Body:
* {
* "locale": "zh-HK",
* "currency": "HKD",
* "categoryIDList": [1, 2],
* "sortOrder": "ID_A",
* "pageIndex": 1,
* "pageSize": 10,
* "imageSize": "500_280",
* "poiIDList": [],
* "keyWord": "",
* "lastUpdateProductID": 0,
* "business": "ACTIVITY",
* "locationIndex": 0
* }
*/
@PostMapping("/product-list")
@Operation(summary = "10.获取产品列表(自动填充位置)")
@SuppressWarnings("unchecked")
public Result<Map<String, Object>> testProductList(@RequestBody Map<String, Object> params) {
log.info("===== 获取产品列表,params: {} =====", params);
try {
// 提取locationIndex并从请求体中移除(不传给产品列表接口)
int locationIndex = params.containsKey("locationIndex")
? Integer.parseInt(params.get("locationIndex").toString()) : 0;
Map<String, Object> productListRequest = new java.util.LinkedHashMap<>(params);
productListRequest.remove("locationIndex");
// 第一步:调用位置列表接口获取locationID和locationType
log.info("第一步:调用位置列表接口,locale=zh-CN,取第{}个位置", locationIndex);
Map<String, Object> locationResult = ctripDistApiService.getLocationList(1, 20);
Object locationData = locationResult.get("data");
if (locationData == null) {
return Result.failed("位置列表接口返回data为空,无法获取locationID");
}
List<Map<String, Object>> locationList =
(List<Map<String, Object>>) ((Map<String, Object>) locationData).get("locationList");
if (locationList == null || locationList.isEmpty()) {
return Result.failed("位置列表为空,无法获取locationID");
}
if (locationIndex >= locationList.size()) {
return Result.failed("locationIndex=" + locationIndex + " 超出位置列表范围(共" + locationList.size() + "个位置)");
}
Map<String, Object> location = locationList.get(locationIndex);
Object locationID = location.get("locationID");
Object locationType = location.get("type");
log.info("获取到位置:locationID={}, type={}, name={}", locationID, locationType, location.get("name"));
// 第二步:用获取到的locationID和locationType填充site和destination
Map<String, Object> siteMap = new java.util.LinkedHashMap<>();
siteMap.put("locationID", locationID);
siteMap.put("locationType", locationType);
Map<String, Object> destinationMap = new java.util.LinkedHashMap<>();
destinationMap.put("locationID", locationID);
destinationMap.put("locationType", locationType);
productListRequest.put("site", siteMap);
productListRequest.put("destination", destinationMap);
log.info("第二步:调用产品列表接口,site/destination locationID={}, locationType={}", locationID, locationType);
// 第三步:调用产品列表接口
Map<String, Object> result = ctripDistApiService.getProductList(productListRequest);
log.info("产品列表返回: {}", result);
// 在返回结果中附加使用的位置信息,方便调试
Map<String, Object> response = new java.util.LinkedHashMap<>();
response.put("usedLocation", location);
response.put("productListResult", result);
return Result.succeed(response, "获取产品列表成功");
} catch (Exception e) {
log.error("获取产品列表失败", e);
return Result.failed("获取产品列表失败: " + e.getMessage());
}
}
// ==================== 11. 获取产品全量列表 ====================
/**
* 获取产品全量列表
* 用途:分批拉取指定业务类型下的全量产品ID及销售状态
* 首次调用 lastMaxId 传 "0",后续将上次返回的 maxId 作为 lastMaxId 继续翻页,
* 直到返回的 productList 为空或数量小于 limit 为止
*
* 调用示例:GET /ctrip/dist/test/all-products?business=ACTIVITY&lastMaxId=0&limit=50
*/
@GetMapping("/all-products")
@Operation(summary = "11.获取产品全量列表")
public Result<Map<String, Object>> testAllProducts(
@RequestParam(defaultValue = "ACTIVITY") String business,
@RequestParam(defaultValue = "0") String lastMaxId,
@RequestParam(defaultValue = "50") int limit) {
log.info("===== 获取产品全量列表,business: {}, lastMaxId: {}, limit: {} =====",
business, lastMaxId, limit);
try {
Map<String, Object> result = ctripDistApiService.getAllProducts(business, lastMaxId, limit);
log.info("产品全量列表返回: success={}, maxId={}, productList size={}",
result.get("success"), result.get("maxId"),
result.get("productList") instanceof java.util.List
? ((java.util.List<?>) result.get("productList")).size() : 0);
return Result.succeed(result, "获取产品全量列表成功");
} catch (Exception e) {
log.error("获取产品全量列表失败", e);
return Result.failed("获取产品全量列表失败: " + e.getMessage());
}
}
// ==================== 辅助方法 ==================== // ==================== 辅助方法 ====================
/** /**
@@ -712,8 +572,8 @@ public class CtripDistTestController {
/** /**
* 解析出行人问卷答案 * 解析出行人问卷答案
* *
* passengers中每个出行人是一个Map,key可以直接传questionCode,也可以传通用姓名字段 * passengers中每个出行人是一个Map,key为questionCode,value为答案值
* 示例: {"name": "张三"} 或 {"P_NAME": "张三"} * 示例: {"P_FIRSTCNAME": "Chao", "P_LASTCNAME": "Du"}
* *
* 系统自动从缓存的问卷模板中匹配questionID和questionTitle * 系统自动从缓存的问卷模板中匹配questionID和questionTitle
* *
@@ -734,28 +594,35 @@ public class CtripDistTestController {
List<Map<String, Object>> passengers = (List<Map<String, Object>>) passengersObj; List<Map<String, Object>> passengers = (List<Map<String, Object>>) passengersObj;
// 构建 questionCode → 模板 的映射 // 构建 questionCode → 模板 的映射
// 携程返回的字段名是 "code"(不是 "questionCode") // 携程返回的字段名是 "code"(不是 "questionCode")
Map<String, Map<String, Object>> templateMap = buildQuestionTemplateMap(questionTemplate); Map<String, Map<String, Object>> templateMap = new LinkedHashMap<>();
for (Map<String, Object> q : questionTemplate) {
String code = getFieldValue(q, "code", "questionCode");
if (code != null) {
templateMap.put(code, q);
}
}
for (Map<String, Object> passengerMap : passengers) { for (Map<String, Object> passengerMap : passengers) {
Map<String, CtripDistBookRequest.QuestionAnswer> answersByCode = new LinkedHashMap<>(); List<CtripDistBookRequest.QuestionAnswer> answers = new ArrayList<>();
for (Map.Entry<String, Object> entry : passengerMap.entrySet()) { for (Map.Entry<String, Object> entry : passengerMap.entrySet()) {
String inputKey = entry.getKey(); String questionCode = entry.getKey();
String answerValue = entry.getValue() != null ? entry.getValue().toString() : ""; String answerValue = entry.getValue() != null ? entry.getValue().toString() : "";
// 从模板匹配 questionID 和 questionTitle // 从模板匹配 questionID 和 questionTitle
Map<String, Object> template = resolveQuestionTemplate(inputKey, questionTemplate, templateMap); Map<String, Object> template = templateMap.get(questionCode);
if (template != null) { if (template != null) {
CtripDistBookRequest.QuestionAnswer answer = buildQuestionAnswer(template, answerValue); CtripDistBookRequest.QuestionAnswer answer = new CtripDistBookRequest.QuestionAnswer();
if (answer.getQuestionCode() == null || answer.getQuestionCode().isEmpty()) { answer.setQuestionID(Long.valueOf(template.get("questionID").toString()));
log.warn("questionCode={} 未能从问卷模板解析出实际 code,跳过", inputKey); answer.setQuestionCode(questionCode);
String title = getFieldValue(template, "title", "questionTitle");
answer.setQuestionTitle(title != null ? title : "");
answer.setAnswerList(Collections.singletonList(answerValue));
answers.add(answer);
} else { } else {
answersByCode.put(answer.getQuestionCode(), answer); log.warn("questionCode={} 在问卷模板中未找到,跳过", questionCode);
}
} else {
log.warn("questionCode={} 在问卷模板中未找到,跳过", inputKey);
} }
} }
result.add(new ArrayList<>(answersByCode.values())); result.add(answers);
} }
} }
@@ -766,84 +633,6 @@ public class CtripDistTestController {
return result; return result;
} }
private Map<String, Map<String, Object>> buildQuestionTemplateMap(List<Map<String, Object>> questionTemplate) {
Map<String, Map<String, Object>> templateMap = new LinkedHashMap<>();
for (Map<String, Object> template : questionTemplate) {
String code = getFieldValue(template, "code", "questionCode");
if (code != null && !code.isEmpty()) {
templateMap.put(code, template);
}
}
return templateMap;
}
private Map<String, Object> resolveQuestionTemplate(String inputKey,
List<Map<String, Object>> questionTemplate,
Map<String, Map<String, Object>> templateMap) {
Map<String, Object> directTemplate = templateMap.get(inputKey);
if (directTemplate != null) {
return directTemplate;
}
if (isPassengerNameKey(inputKey)) {
return findPreferredChineseNameTemplate(questionTemplate, templateMap);
}
return null;
}
private Map<String, Object> findPreferredChineseNameTemplate(List<Map<String, Object>> questionTemplate,
Map<String, Map<String, Object>> templateMap) {
return findQuestionTemplateByCodes(questionTemplate, templateMap, "P_CNAME", "P_NAME");
}
private Map<String, Object> findQuestionTemplateByCodes(List<Map<String, Object>> questionTemplate,
Map<String, Map<String, Object>> templateMap,
String... preferredCodes) {
for (String preferredCode : preferredCodes) {
Map<String, Object> template = templateMap.get(preferredCode);
if (template != null) {
return template;
}
}
for (Map<String, Object> template : questionTemplate) {
String code = getFieldValue(template, "code", "questionCode");
for (String preferredCode : preferredCodes) {
if (preferredCode.equalsIgnoreCase(code)) {
return template;
}
}
}
return null;
}
private boolean isPassengerNameKey(String inputKey) {
if (inputKey == null) {
return false;
}
return Arrays.asList("name", "passengerName", "passengerCname", "cname", "P_NAME", "P_CNAME")
.contains(inputKey);
}
private CtripDistBookRequest.QuestionAnswer buildQuestionAnswer(Map<String, Object> template, String answerValue) {
CtripDistBookRequest.QuestionAnswer answer = new CtripDistBookRequest.QuestionAnswer();
String questionId = getFieldValue(template, "questionID", "id");
if (questionId != null && !questionId.isEmpty()) {
answer.setQuestionID(Long.valueOf(questionId));
}
String questionCode = getFieldValue(template, "code", "questionCode");
answer.setQuestionCode(normalizeQuestionCode(questionCode));
String title = getFieldValue(template, "title", "questionTitle");
answer.setQuestionTitle(title != null ? title : "");
answer.setAnswerList(Collections.singletonList(answerValue));
return answer;
}
private String normalizeQuestionCode(String questionCode) {
if ("P_NAME".equalsIgnoreCase(questionCode)) {
return "P_CNAME";
}
return questionCode != null ? questionCode : "";
}
/** /**
* 构建测试下单请求(通用版) * 构建测试下单请求(通用版)
* *
@@ -39,9 +39,6 @@ public class CtripDistOrder {
@TableField("distributor_order_id") @TableField("distributor_order_id")
private String distributorOrderId; private String distributorOrderId;
@TableField("mobile")
private String mobile;
@TableField("order_amount") @TableField("order_amount")
private BigDecimal orderAmount; private BigDecimal orderAmount;
@@ -98,31 +98,4 @@ public interface ICtripDistApiService {
* @return 响应 * @return 响应
*/ */
Map<String, Object> simulateConfirm(Map<String, Object> requestBody); Map<String, Object> simulateConfirm(Map<String, Object> requestBody);
/**
* 获取位置列表
*
* @param pageIndex 页码
* @param pageSize 每页数量
* @return 位置列表
*/
Map<String, Object> getLocationList(int pageIndex, int pageSize);
/**
* 获取产品列表
*
* @param request 请求参数
* @return 产品列表
*/
Map<String, Object> getProductList(Map<String, Object> request);
/**
* 获取产品全量列表
*
* @param business 业务类型(如 ACTIVITY)
* @param lastMaxId 上次返回的maxId,首次传"0"
* @param limit 每页条数
* @return 产品全量列表
*/
Map<String, Object> getAllProducts(String business, String lastMaxId, int limit);
} }
@@ -117,35 +117,12 @@ public class CtripDistApiServiceImpl implements ICtripDistApiService {
return callApi(config.getIcode().getSimulateConfirm(), requestBody, Map.class); return callApi(config.getIcode().getSimulateConfirm(), requestBody, Map.class);
} }
@Override
public Map<String, Object> getLocationList(int pageIndex, int pageSize) {
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("locale", "zh-CN");
requestBody.put("pageIndex", pageIndex);
requestBody.put("pageSize", pageSize);
return callApi(config.getIcode().getLocationList(), requestBody, Map.class);
}
@Override
public Map<String, Object> getProductList(Map<String, Object> request) {
return callApi(config.getIcode().getProductList(), request, Map.class);
}
@Override
public Map<String, Object> getAllProducts(String business, String lastMaxId, int limit) {
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("business", business);
requestBody.put("lastMaxId", lastMaxId);
requestBody.put("limit", limit);
return callApi(config.getIcode().getAllProducts(), requestBody, Map.class);
}
private <T> T callApi(String icode, Object requestBody, Class<T> responseType) { private <T> T callApi(String icode, Object requestBody, Class<T> responseType) {
String token = tokenService.getAccessToken(); String token = tokenService.getAccessToken();
String uuid = UUID.randomUUID().toString().replace("-", ""); String uuid = UUID.randomUUID().toString().replace("-", "");
String url = String.format("%s?aid=%s&sid=%s&icode=%s&uuid=%s&token=%s", String url = String.format("%s?aid=%s&sid=%s&icode=%s&uuid=%s&token=%s",
config.getApiUrl(), config.getAid(), config.getSid(), icode, uuid, token); config.getApiUrl(), config.getAid(), config.getSid(), icode, uuid, token);
log.info("请求地址是:{}",url);
String requestJson; String requestJson;
try { try {
requestJson = objectMapper.writeValueAsString(requestBody); requestJson = objectMapper.writeValueAsString(requestBody);
@@ -16,10 +16,8 @@ import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -58,24 +56,20 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
Map<String, Object> bookInfo = ctripDistApiService.getBookInfo(ctripProductId, packageId, resourceId); Map<String, Object> bookInfo = ctripDistApiService.getBookInfo(ctripProductId, packageId, resourceId);
log.info("携程分销商下单填写信息,orderNo: {}, bookInfo: {}", orderNo, bookInfo); log.info("携程分销商下单填写信息,orderNo: {}, bookInfo: {}", orderNo, bookInfo);
// 校验问卷是否属于当前支持自动填充的范围 // 校验产品是否要求额外乘客问卷(如身份证等),如果要求则无法自动下单
validateBookInfo(bookInfo, orderNo); validateBookInfo(bookInfo, orderNo);
String distributorOrderId = orderNo; String distributorOrderId = orderNo;
BigDecimal amountYuan = new BigDecimal(orderAmount).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP); BigDecimal amountYuan = new BigDecimal(orderAmount).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
CtripDistBookRequest checkRequest = buildBookRequest( CtripDistBookRequest request = buildBookRequest(distributorOrderId, ctripProductId, packageId, resourceId, amountYuan, mobile);
distributorOrderId, ctripProductId, packageId, resourceId, amountYuan, mobile, bookInfo, false);
// 可订检查:下单前确认资源可预订 // 可订检查:下单前确认资源可预订
boolean available = ctripDistApiService.checkAvailability(checkRequest); boolean available = ctripDistApiService.checkAvailability(request);
if (!available) { if (!available) {
throw new RuntimeException("携程可订检查失败,资源不可预订,orderNo: " + orderNo); throw new RuntimeException("携程可订检查失败,资源不可预订,orderNo: " + orderNo);
} }
log.info("携程可订检查通过,orderNo: {}", orderNo); log.info("携程可订检查通过,orderNo: {}", orderNo);
CtripDistBookRequest createRequest = buildBookRequest(
distributorOrderId, ctripProductId, packageId, resourceId, amountYuan, mobile, bookInfo, true);
CtripDistOrder order = new CtripDistOrder(); CtripDistOrder order = new CtripDistOrder();
order.setTenantId(tenantId); order.setTenantId(tenantId);
order.setOrderNo(orderNo); order.setOrderNo(orderNo);
@@ -83,7 +77,6 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
order.setCtripPackageId(packageId); order.setCtripPackageId(packageId);
order.setCtripResourceId(resourceId); order.setCtripResourceId(resourceId);
order.setDistributorOrderId(distributorOrderId); order.setDistributorOrderId(distributorOrderId);
order.setMobile(mobile);
order.setOrderAmount(amountYuan); order.setOrderAmount(amountYuan);
order.setCurrency(config.getCurrency()); order.setCurrency(config.getCurrency());
order.setCtripOrderStatus("CREATING"); order.setCtripOrderStatus("CREATING");
@@ -94,7 +87,7 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
ctripDistOrderMapper.insert(order); ctripDistOrderMapper.insert(order);
try { try {
CtripDistBookResponse response = ctripDistApiService.createOrder(createRequest); CtripDistBookResponse response = ctripDistApiService.createOrder(request);
if (response != null && response.isSuccess() && response.getData() != null && response.getData().getOrderId() != null) { if (response != null && response.isSuccess() && response.getData() != null && response.getData().getOrderId() != null) {
order.setCtripOrderId(response.getData().getOrderId()); order.setCtripOrderId(response.getData().getOrderId());
order.setCtripOrderStatus("CONFIRMED"); order.setCtripOrderStatus("CONFIRMED");
@@ -171,8 +164,7 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
private static final String DEFAULT_CONTACT_EMAIL = "1098974448@qq.com"; private static final String DEFAULT_CONTACT_EMAIL = "1098974448@qq.com";
private CtripDistBookRequest buildBookRequest(String distributorOrderId, Long productId, Long packageId, private CtripDistBookRequest buildBookRequest(String distributorOrderId, Long productId, Long packageId,
Long resourceId, BigDecimal amountYuan, String userMobile, Long resourceId, BigDecimal amountYuan, String userMobile) {
Map<String, Object> bookInfo, boolean includeAreaCode) {
CtripDistBookRequest request = new CtripDistBookRequest(); CtripDistBookRequest request = new CtripDistBookRequest();
request.setLocale(config.getLocale()); request.setLocale(config.getLocale());
request.setCurrency(config.getCurrency()); request.setCurrency(config.getCurrency());
@@ -192,7 +184,7 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
CtripDistBookRequest.Passenger passenger = new CtripDistBookRequest.Passenger(); CtripDistBookRequest.Passenger passenger = new CtripDistBookRequest.Passenger();
passenger.setPackageID(packageId); passenger.setPackageID(packageId);
passenger.setResourceID(resourceId); passenger.setResourceID(resourceId);
passenger.setQuestionAnswerList(buildPassengerQuestionAnswers(bookInfo, contactMobile, includeAreaCode)); passenger.setQuestionAnswerList(new ArrayList<>());
request.setPassengerList(Collections.singletonList(passenger)); request.setPassengerList(Collections.singletonList(passenger));
CtripDistBookRequest.OrderResource orderResource = new CtripDistBookRequest.OrderResource(); CtripDistBookRequest.OrderResource orderResource = new CtripDistBookRequest.OrderResource();
@@ -210,33 +202,6 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
return request; return request;
} }
@SuppressWarnings("unchecked")
private List<CtripDistBookRequest.QuestionAnswer> buildPassengerQuestionAnswers(Map<String, Object> bookInfo,
String contactMobile,
boolean includeAreaCode) {
List<CtripDistBookRequest.QuestionAnswer> answers = new ArrayList<>();
if (bookInfo == null || bookInfo.get("data") == null) {
return answers;
}
Map<String, Object> data = (Map<String, Object>) bookInfo.get("data");
Object questionList = data.get("passengerQuestionList");
if (!(questionList instanceof List)) {
return answers;
}
for (Object item : (List<?>) questionList) {
if (!(item instanceof Map)) {
continue;
}
Map<String, Object> question = (Map<String, Object>) item;
String answerValue = resolvePassengerAnswerValue(question, contactMobile, includeAreaCode);
if (answerValue == null) {
continue;
}
answers.add(buildQuestionAnswer(question, answerValue));
}
return answers;
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private Long extractPackageId(Map<String, Object> productDetail) { private Long extractPackageId(Map<String, Object> productDetail) {
Map<String, Object> data = (Map<String, Object>) productDetail.get("data"); Map<String, Object> data = (Map<String, Object>) productDetail.get("data");
@@ -261,7 +226,7 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
/** /**
* 校验下单填写信息 * 校验下单填写信息
* 当前仅支持自动填充姓名、手机号和手机号区号 * 如果产品要求额外乘客问卷(如身份证等),当前平台无法提供,拒绝自动下单
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void validateBookInfo(Map<String, Object> bookInfo, String orderNo) { private void validateBookInfo(Map<String, Object> bookInfo, String orderNo) {
@@ -272,72 +237,10 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
Map<String, Object> data = (Map<String, Object>) bookInfo.get("data"); Map<String, Object> data = (Map<String, Object>) bookInfo.get("data");
Object questionList = data.get("passengerQuestionList"); Object questionList = data.get("passengerQuestionList");
if (questionList instanceof List) { if (questionList instanceof List) {
Set<String> unsupportedCodes = new LinkedHashSet<>(); List<?> questions = (List<?>) questionList;
for (Object item : (List<?>) questionList) { if (!questions.isEmpty()) {
if (!(item instanceof Map)) { throw new RuntimeException("该携程产品要求填写额外乘客信息(如身份证等),无法自动下单,orderNo: " + orderNo);
continue;
}
Map<String, Object> question = (Map<String, Object>) item;
String questionCode = normalizeQuestionCode(getFieldValue(question, "code", "questionCode"));
if (!isSupportedPassengerQuestion(questionCode)) {
unsupportedCodes.add(questionCode);
}
}
if (!unsupportedCodes.isEmpty()) {
throw new RuntimeException("该携程产品包含暂不支持自动填写的乘客信息,questionCode="
+ unsupportedCodes + ",orderNo: " + orderNo);
} }
} }
} }
private boolean isSupportedPassengerQuestion(String questionCode) {
return "P_CNAME".equalsIgnoreCase(questionCode)
|| "P_TELPHONE".equalsIgnoreCase(questionCode)
|| "P_TELPHONE_AREA_CODE".equalsIgnoreCase(questionCode);
}
private String resolvePassengerAnswerValue(Map<String, Object> question, String contactMobile,
boolean includeAreaCode) {
String questionCode = normalizeQuestionCode(getFieldValue(question, "code", "questionCode"));
if ("P_CNAME".equalsIgnoreCase(questionCode)) {
return DEFAULT_CONTACT_NAME;
}
if ("P_TELPHONE".equalsIgnoreCase(questionCode)) {
return contactMobile;
}
if ("P_TELPHONE_AREA_CODE".equalsIgnoreCase(questionCode)) {
return includeAreaCode ? "+86" : null;
}
return null;
}
private CtripDistBookRequest.QuestionAnswer buildQuestionAnswer(Map<String, Object> question, String answerValue) {
CtripDistBookRequest.QuestionAnswer answer = new CtripDistBookRequest.QuestionAnswer();
String questionId = getFieldValue(question, "questionID", "id");
if (questionId != null && !questionId.isEmpty()) {
answer.setQuestionID(Long.valueOf(questionId));
}
answer.setQuestionCode(normalizeQuestionCode(getFieldValue(question, "code", "questionCode")));
String title = getFieldValue(question, "title", "questionTitle");
answer.setQuestionTitle(title != null ? title : "");
answer.setAnswerList(Collections.singletonList(answerValue));
return answer;
}
private String normalizeQuestionCode(String questionCode) {
if ("P_NAME".equalsIgnoreCase(questionCode)) {
return "P_CNAME";
}
return questionCode != null ? questionCode : "";
}
private String getFieldValue(Map<String, Object> map, String... keys) {
for (String key : keys) {
Object value = map.get(key);
if (value != null) {
return value.toString();
}
}
return null;
}
} }
@@ -1,26 +1,16 @@
package com.central.coupon.task; package com.central.coupon.task;
import com.central.coupon.controller.CtripConsumedController;
import com.central.coupon.entity.CtripContact;
import com.central.coupon.entity.CtripDistOrder; import com.central.coupon.entity.CtripDistOrder;
import com.central.coupon.entity.CtripOrder;
import com.central.coupon.entity.CtripOrderItem;
import com.central.coupon.mapper.CtripContactMapper;
import com.central.coupon.mapper.CtripDistOrderMapper; import com.central.coupon.mapper.CtripDistOrderMapper;
import com.central.coupon.mapper.CtripOrderItemMapper; import com.central.coupon.model.CtripDistBookingDetailResponse;
import com.central.coupon.mapper.CtripOrderMapper; import com.central.coupon.service.ICtripDistApiService;
import com.central.coupon.model.CtripConsumedNoticeResponse;
import com.central.coupon.service.CtripConsumedService;
import com.central.coupon.service.IOrderDetailService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
@Slf4j @Slf4j
@Component @Component
@@ -30,19 +20,7 @@ public class CtripDistConsumeTask {
private CtripDistOrderMapper ctripDistOrderMapper; private CtripDistOrderMapper ctripDistOrderMapper;
@Autowired @Autowired
private CtripContactMapper ctripContactMapper; private ICtripDistApiService ctripDistApiService;
@Autowired
private CtripOrderMapper ctripOrderMapper;
@Autowired
private CtripOrderItemMapper ctripOrderItemMapper;
@Autowired
private CtripConsumedService ctripConsumedService;
@Autowired
private IOrderDetailService orderDetailService;
/** /**
* 每天凌晨3点执行:核销2天前创建且未核销的携程分销订单 * 每天凌晨3点执行:核销2天前创建且未核销的携程分销订单
@@ -51,18 +29,17 @@ public class CtripDistConsumeTask {
public void autoConsumeCtripDistOrders() { public void autoConsumeCtripDistOrders() {
log.info("开始自动核销携程分销订单"); log.info("开始自动核销携程分销订单");
try { try {
// 1. 查询2天前创建且未核销的CtripDistOrder List<CtripDistOrder> pendingOrders = ctripDistOrderMapper.selectPendingConsumeOrders(2);
List<CtripDistOrder> pendingOrders = ctripDistOrderMapper.selectPendingConsumeOrders(3);
log.info("待核销的携程分销订单数量: {}", pendingOrders.size()); log.info("待核销的携程分销订单数量: {}", pendingOrders.size());
for (CtripDistOrder distOrder : pendingOrders) { for (CtripDistOrder order : pendingOrders) {
try { try {
consumeOrder(distOrder); consumeOrder(order);
} catch (Exception e) { } catch (Exception e) {
log.error("核销携程分销订单失败,orderNo: {}", distOrder.getOrderNo(), e); log.error("核销携程分销订单失败,orderNo: {}", order.getOrderNo(), e);
distOrder.setConsumeStatus(2); order.setConsumeStatus(2);
distOrder.setErrorMsg("核销失败: " + e.getMessage()); order.setErrorMsg("核销失败: " + e.getMessage());
ctripDistOrderMapper.updateById(distOrder); ctripDistOrderMapper.updateById(order);
} }
} }
log.info("携程分销订单自动核销完成"); log.info("携程分销订单自动核销完成");
@@ -71,121 +48,43 @@ public class CtripDistConsumeTask {
} }
} }
private void consumeOrder(CtripDistOrder distOrder) { /**
String mobile = distOrder.getMobile(); * 核销单个订单
log.info("开始核销携程分销订单,orderNo: {}, mobile: {}", distOrder.getOrderNo(), mobile); * 先查询携程订单状态确认为CONFIRMED,然后标记为已核销
*/
private void consumeOrder(CtripDistOrder order) {
log.info("开始核销携程分销订单,orderNo: {}, ctripOrderId: {}",
order.getOrderNo(), order.getCtripOrderId());
if (mobile == null || mobile.isEmpty()) { // 查询携程订单当前状态
distOrder.setConsumeStatus(2); CtripDistBookingDetailResponse detail = ctripDistApiService.getOrderDetail(order.getCtripOrderId());
distOrder.setErrorMsg("分销订单手机号为空,无法核销"); if (detail != null && detail.isSuccess() && detail.getData() != null
ctripDistOrderMapper.updateById(distOrder); && detail.getData().getOrder() != null) {
log.warn("分销订单手机号为空,跳过核销,orderNo: {}", distOrder.getOrderNo()); String ctripStatus = detail.getData().getOrder().getOrderStatus();
return; log.info("携程订单当前状态: {}, orderNo: {}", ctripStatus, order.getOrderNo());
}
// 2. 根据手机号通过联系人表查找CtripOrder if ("CONFIRMED".equals(ctripStatus)) {
List<CtripContact> contacts = ctripContactMapper.selectByMobile(mobile); // 订单状态正常,执行核销
if (contacts == null || contacts.isEmpty()) { order.setConsumeStatus(1);
distOrder.setConsumeStatus(2); order.setConsumeTime(LocalDateTime.now());
distOrder.setErrorMsg("未找到手机号对应的携程联系人记录"); order.setCtripOrderStatus("CONSUMED");
ctripDistOrderMapper.updateById(distOrder); ctripDistOrderMapper.updateById(order);
log.warn("未找到手机号 {} 对应的联系人记录,orderNo: {}", mobile, distOrder.getOrderNo()); log.info("携程分销订单核销成功,orderNo: {}", order.getOrderNo());
return; } else if ("CANCELLED".equals(ctripStatus) || "CANCELLED_RESERVATION".equals(ctripStatus)) {
} // 订单已被取消,更新状态
order.setCtripOrderStatus(ctripStatus);
List<Long> orderIds = contacts.stream() order.setConsumeStatus(2);
.map(CtripContact::getOrderId) order.setErrorMsg("携程订单已被取消,无法核销");
.distinct() ctripDistOrderMapper.updateById(order);
.collect(Collectors.toList()); log.warn("携程订单已取消,跳过核销,orderNo: {}", order.getOrderNo());
// 筛选状态为PAYMENT_CONFIRMED(13)的订单
List<CtripOrder> confirmedOrders = new ArrayList<>();
for (Long orderId : orderIds) {
CtripOrder ctripOrder = ctripOrderMapper.selectById(orderId);
if (ctripOrder != null && Integer.valueOf(13).equals(ctripOrder.getStatus())) {
confirmedOrders.add(ctripOrder);
}
}
if (confirmedOrders.isEmpty()) {
distOrder.setConsumeStatus(2);
distOrder.setErrorMsg("未找到状态为PAYMENT_CONFIRMED的携程订单");
ctripDistOrderMapper.updateById(distOrder);
log.warn("手机号 {} 无PAYMENT_CONFIRMED状态的订单,orderNo: {}", mobile, distOrder.getOrderNo());
return;
}
// 3. 对每个符合条件的CtripOrder执行核销
boolean anySuccess = false;
StringBuilder errorMsgs = new StringBuilder();
for (CtripOrder ctripOrder : confirmedOrders) {
try {
// 建立订单关联关系
if (ctripOrder.getOrderNo() == null || ctripOrder.getOrderNo().trim().isEmpty()) {
ctripOrder.setOrderNo(distOrder.getOrderNo());
ctripOrderMapper.updateById(ctripOrder);
log.info("建立订单关联关系,otaOrderId: {}, orderNo: {}", ctripOrder.getOtaOrderId(), distOrder.getOrderNo());
}
// 验证订单是否可核销
if (!orderDetailService.validateOrderForConsume(ctripOrder.getOtaOrderId())) {
log.warn("订单不可核销,otaOrderId: {}", ctripOrder.getOtaOrderId());
continue;
}
// 查询订单项,逐项核销
List<CtripOrderItem> orderItems = ctripOrderItemMapper.selectByOrderId(ctripOrder.getId());
if (orderItems == null || orderItems.isEmpty()) {
log.warn("订单无订单项,otaOrderId: {}", ctripOrder.getOtaOrderId());
continue;
}
for (CtripOrderItem item : orderItems) {
if (item.getQuantity() == null || item.getQuantity() <= 0) {
continue;
}
CtripConsumedController.CtripConsumeRequest request = new CtripConsumedController.CtripConsumeRequest();
request.setOtaOrderId(ctripOrder.getOtaOrderId());
request.setSupplierOrderId(ctripOrder.getSupplierOrderId());
request.setItemId(item.getItemId());
request.setUseQuantity(item.getQuantity());
request.setRemark("分销订单自动核销,orderNo: " + distOrder.getOrderNo());
CtripConsumedNoticeResponse response = ctripConsumedService.consumeOrder(request);
boolean success = response != null && "0000".equals(response.getHeader().getResultCode());
if (success) {
log.info("核销成功,otaOrderId: {}, itemId: {}", ctripOrder.getOtaOrderId(), item.getItemId());
anySuccess = true;
} else { } else {
String errMsg = response != null ? response.getHeader().getResultMessage() : "未知错误"; log.warn("携程订单状态不适合核销: {},orderNo: {}", ctripStatus, order.getOrderNo());
log.error("核销失败,otaOrderId: {}, itemId: {}, error: {}", ctripOrder.getOtaOrderId(), item.getItemId(), errMsg);
errorMsgs.append("otaOrderId=").append(ctripOrder.getOtaOrderId())
.append(",itemId=").append(item.getItemId())
.append(":").append(errMsg).append("; ");
} }
}
} catch (Exception e) {
log.error("核销携程订单异常,otaOrderId: {}", ctripOrder.getOtaOrderId(), e);
errorMsgs.append("otaOrderId=").append(ctripOrder.getOtaOrderId())
.append(":").append(e.getMessage()).append("; ");
}
}
// 4. 更新CtripDistOrder状态
if (anySuccess) {
distOrder.setConsumeStatus(1);
distOrder.setConsumeTime(LocalDateTime.now());
distOrder.setCtripOrderStatus("CONSUMED");
distOrder.setErrorMsg(errorMsgs.length() > 0 ? "部分核销异常: " + errorMsgs : null);
log.info("携程分销订单核销成功,orderNo: {}", distOrder.getOrderNo());
} else { } else {
distOrder.setConsumeStatus(2); log.error("查询携程订单详情失败,orderNo: {}", order.getOrderNo());
distOrder.setErrorMsg(errorMsgs.length() > 0 ? errorMsgs.toString() : "所有订单核销均失败"); order.setConsumeStatus(2);
log.warn("携程分销订单核销失败,orderNo: {}", distOrder.getOrderNo()); order.setErrorMsg("查询携程订单详情失败");
ctripDistOrderMapper.updateById(order);
} }
ctripDistOrderMapper.updateById(distOrder);
} }
} }
@@ -49,7 +49,7 @@ public class BoatCommandManager {
* 发送命令 * 发送命令
* *
* @param deviceSn 设备SN * @param deviceSn 设备SN
* @param commandType 命令类型(flighttask_prepare/flighttask_pause/flighttask_recovery/flighttask_undo) * @param commandType 命令类型(flighttask_prepare/flighttask_pause/flighttask_recovery/flighttask_undo/flighttask_slowly)
* @param params 命令参数 * @param params 命令参数
* @return 命令ID * @return 命令ID
*/ */
@@ -187,6 +187,12 @@ public class BoatCommandManager {
} }
break; break;
case "flighttask_slowly":
// 慢速行驶
data.put("order_no", params.getString("order_no"));
data.put("speed", params.getInteger("speed"));
break;
default: default:
data = params; data = params;
break; break;
@@ -2,6 +2,7 @@ package com.central.device.controller;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.device.model.dto.BoatManualControlDTO; import com.central.device.model.dto.BoatManualControlDTO;
import com.central.device.model.dto.BoatSlowlyDriveDTO;
import com.central.device.service.IBoatControlService; import com.central.device.service.IBoatControlService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
@@ -61,6 +62,15 @@ public class BoatCommandController {
return Result.succeed(null, "终止任务指令已下发"); return Result.succeed(null, "终止任务指令已下发");
} }
@Operation(summary = "慢速行驶")
@PostMapping("/slowly")
public Result<Void> slowly(
@Parameter(description = "设备SN") @RequestParam String deviceSn,
@RequestBody @Validated BoatSlowlyDriveDTO dto) {
boatControlService.slowly(deviceSn, dto);
return Result.succeed(null, "慢速行驶指令已下发");
}
@Operation(summary = "返回起点") @Operation(summary = "返回起点")
@PostMapping("/return") @PostMapping("/return")
public Result<Void> returnToStart( public Result<Void> returnToStart(
@@ -13,9 +13,19 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.List; import java.util.List;
/** /**
@@ -56,6 +66,21 @@ public class BoatRouteController {
return Result.succeed(detail); return Result.succeed(detail);
} }
@Operation(summary = "分页查询无人船航线列表")
@GetMapping("/page")
public Result<Page<BoatRouteListVO>> pageRoutes(
@Parameter(description = "航线名称") @RequestParam(required = false) String routeName,
@Parameter(description = "设备SN") @RequestParam(required = false) String deviceSn,
@Parameter(description = "创建开始时间") @RequestParam(required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
@Parameter(description = "创建结束时间") @RequestParam(required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
@Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size) {
Page<BoatRouteListVO> pageResult = boatRouteService.pageRoutes(routeName, deviceSn, startTime, endTime, page, size);
return Result.succeed(pageResult);
}
@Operation(summary = "获取设备绑定的航线列表") @Operation(summary = "获取设备绑定的航线列表")
@GetMapping("/list/device/{deviceSn}") @GetMapping("/list/device/{deviceSn}")
public Result<List<BoatRouteListVO>> listByDeviceSn( public Result<List<BoatRouteListVO>> listByDeviceSn(
@@ -28,7 +28,6 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
/** /**
@@ -276,87 +275,6 @@ public class DeviceCommandController {
} }
} }
/**
* 指点飞行 - 首次飞向目标点
* 创建 fly_to_point 会话,flyToId = missionCode
*/
@Operation(summary = "无人机指点飞行 - 飞向目标")
@PostMapping("/flyToPoint")
public Result<String> flyToPoint(@RequestBody FlyToPointRequest request) {
log.info("收到指点飞行(首次)命令: device={}, flyToId={}, target=({}, {}, {})",
request.getDeviceSn(), request.getFlyToId(),
request.getLatitude(), request.getLongitude(), request.getHeight());
try {
JSONObject params = new JSONObject();
params.put("fly_to_id", request.getFlyToId());
params.put("latitude", request.getLatitude());
params.put("longitude", request.getLongitude());
params.put("height", request.getHeight() != null ? request.getHeight() : 100f);
params.put("max_speed", request.getMaxSpeed() != null ? request.getMaxSpeed() : 12f);
String commandId = commandManager.sendCommand(
request.getDeviceSn(),
"fly_to_point",
params
);
return Result.succeed(commandId, "指点飞行命令已发送");
} catch (Exception e) {
log.error("发送指点飞行命令失败: device={}, error={}", request.getDeviceSn(), e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 指点飞行 - 更新目标点(连续指点)
* 打断当前飞行,立即转向新目标;设备协议不含 fly_to_id,仅传 max_speed + points
*/
@Operation(summary = "无人机指点飞行 - 更新目标点")
@PostMapping("/flyToPointUpdate")
public Result<String> flyToPointUpdate(@RequestBody FlyToPointUpdateRequest request) {
log.info("收到指点飞行(更新)命令: device={}, target=({}, {}, {})",
request.getDeviceSn(), request.getLatitude(), request.getLongitude(), request.getHeight());
try {
JSONObject params = new JSONObject();
params.put("latitude", request.getLatitude());
params.put("longitude", request.getLongitude());
params.put("height", request.getHeight() != null ? request.getHeight() : 100f);
params.put("max_speed", request.getMaxSpeed() != null ? request.getMaxSpeed() : 12f);
String commandId = commandManager.sendCommand(
request.getDeviceSn(),
"fly_to_point_update",
params
);
return Result.succeed(commandId, "目标更新命令已发送");
} catch (Exception e) {
log.error("发送目标更新命令失败: device={}, error={}", request.getDeviceSn(), e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 指点飞行 - 停止指点飞行
*/
@Operation(summary = "无人机指点飞行 - 停止")
@PostMapping("/flyToPointStop")
public Result<String> flyToPointStop(@RequestParam String deviceSn) {
log.info("收到停止指点飞行命令: device={}", deviceSn);
try {
String commandId = commandManager.sendCommand(
deviceSn,
"fly_to_point_stop",
new JSONObject()
);
return Result.succeed(commandId, "停止指点飞行命令已发送");
} catch (Exception e) {
log.error("发送停止指点飞行命令失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/** /**
* 开始录像 * 开始录像
*/ */
@@ -507,57 +425,6 @@ public class DeviceCommandController {
} }
} }
/**
* 切换直播镜头(如切换到变焦镜头)
*/
@Operation(summary = "切换直播镜头")
@PostMapping("/liveLensChange")
public Result<String> liveLensChange(@RequestBody Map<String, Object> request) {
String deviceSn = (String) request.get("deviceSn");
String videoType = (String) request.get("videoType");
log.info("切换直播镜头: device={}, videoType={}", deviceSn, videoType);
try {
JSONObject params = new JSONObject();
params.put("video_type", videoType != null ? videoType : "zoom");
String commandId = commandManager.sendCommand(deviceSn, "live_lens_change", params);
return Result.succeed(commandId, "镜头切换命令已发送");
} catch (Exception e) {
log.error("切换镜头失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/**
* 设置变焦倍数
*/
@Operation(summary = "设置变焦倍数")
@PostMapping("/cameraFocalLengthSet")
public Result<String> cameraFocalLengthSet(@RequestBody Map<String, Object> request) {
String deviceSn = (String) request.get("deviceSn");
Double zoomFactor = request.get("zoomFactor") != null ?
Double.parseDouble(request.get("zoomFactor").toString()) : 2.0;
// 范围限制 2~200
zoomFactor = Math.max(2, Math.min(200, zoomFactor));
log.info("设置变焦: device={}, zoomFactor={}", deviceSn, zoomFactor);
try {
JSONObject params = new JSONObject();
params.put("camera_type", "zoom");
params.put("zoom_factor", zoomFactor);
String commandId = commandManager.sendCommand(deviceSn, "camera_focal_length_set", params);
return Result.succeed(commandId, "变焦命令已发送");
} catch (Exception e) {
log.error("设置变焦失败: device={}, error={}", deviceSn, e.getMessage());
return Result.failed("命令发送失败: " + e.getMessage());
}
}
/** /**
* 执行航线任务 * 执行航线任务
* 参考writeProperties逻辑,用于航线任务执行(不包含订单业务逻辑和幂等性检查) * 参考writeProperties逻辑,用于航线任务执行(不包含订单业务逻辑和幂等性检查)
@@ -779,43 +646,6 @@ public class DeviceCommandController {
private Boolean locked; private Boolean locked;
} }
/**
* 指点飞行(首次飞向目标)请求参数
*/
@Data
public static class FlyToPointRequest {
/** 设备SN */
private String deviceSn;
/** 飞行会话ID(= missionCode) */
private String flyToId;
/** 目标纬度 */
private Double latitude;
/** 目标经度 */
private Double longitude;
/** 目标椭球高(前端计算:Cartographic.height + 用户飞行高度) */
private Float height;
/** 最大飞行速度(m/s),默认 12 */
private Float maxSpeed;
}
/**
* 指点飞行更新目标(连续指点)请求参数
* 注意:设备协议不含 fly_to_id,仅传 max_speed + points
*/
@Data
public static class FlyToPointUpdateRequest {
/** 设备SN */
private String deviceSn;
/** 目标纬度 */
private Double latitude;
/** 目标经度 */
private Double longitude;
/** 目标椭球高 */
private Float height;
/** 最大飞行速度(m/s),默认 12 */
private Float maxSpeed;
}
@Data @Data
public static class CommandStatusDTO { public static class CommandStatusDTO {
private String commandId; private String commandId;
@@ -10,7 +10,7 @@ public enum ControlEnum {
TAKEOFF_TO_POINT("takeoff_to_point"), TAKEOFF_TO_POINT("takeoff_to_point"),
FLY_TO_POINT("fly_to_point"), FLY_TO_POINT("fly_to_point"),
FLY_TO_POINT_STOP("fly_to_point_stop"), FLY_TO_POINT_STOP("fly_to_point_stop"),
FLY_TO_POINT_UPDATE("fly_to_point_update"), FLY_TO_POINT_UPDATE("fly_to_point_stop"),
FLIGHTTASK_PAUSE("flighttask_pause"), FLIGHTTASK_PAUSE("flighttask_pause"),
FLIGHTTASK_PREPARE ("flighttask_prepare"), FLIGHTTASK_PREPARE ("flighttask_prepare"),
FLIGHTTASK_RECOVERY("flighttask_recovery"), FLIGHTTASK_RECOVERY("flighttask_recovery"),
@@ -88,20 +88,5 @@ public class ControlMessageConstant {
} }
public final static String LIVE_LENS_CHANGE = "{\n" +
"\t\"data\": {\n" +
"\t\t\"video_type\": video_type\n" +
"\t},\n" +
"\t\"method\": \"live_lens_change\"\n" +
"}";
public final static String CAMERA_FOCAL_LENGTH_SET = "{\n" +
"\t\"data\": {\n" +
"\t\t\"camera_type\": camera_type,\n" +
"\t\t\"zoom_factor\": zoom_factor\n" +
"\t},\n" +
"\t\"method\": \"camera_focal_length_set\"\n" +
"}";
} }
@@ -0,0 +1,25 @@
package com.central.device.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
/**
* 无人船慢速行驶DTO
*
* @author Codex
* @date 2026-04-20
*/
@Data
@Schema(description = "无人船慢速行驶请求")
public class BoatSlowlyDriveDTO {
@Schema(description = "任务编码(对应 order_no)", required = true, example = "562026040600002")
@NotBlank(message = "任务编码不能为空")
private String missionCode;
@Schema(description = "慢速行驶速度", required = true, example = "30")
@NotNull(message = "速度不能为空")
private Integer speed;
}
@@ -1,6 +1,7 @@
package com.central.device.service; package com.central.device.service;
import com.central.device.model.dto.BoatManualControlDTO; import com.central.device.model.dto.BoatManualControlDTO;
import com.central.device.model.dto.BoatSlowlyDriveDTO;
/** /**
* 无人船控制服务接口 * 无人船控制服务接口
@@ -44,6 +45,14 @@ public interface IBoatControlService {
*/ */
void undoTask(String deviceSn, String missionCode); void undoTask(String deviceSn, String missionCode);
/**
* 慢速行驶
*
* @param deviceSn 设备SN
* @param dto 慢速行驶参数
*/
void slowly(String deviceSn, BoatSlowlyDriveDTO dto);
/** /**
* 返回起点 * 返回起点
* *
@@ -9,6 +9,7 @@ import com.central.device.model.vo.BoatRouteDetailVO;
import com.central.device.model.vo.BoatRouteListVO; import com.central.device.model.vo.BoatRouteListVO;
import com.central.device.model.vo.RouteValidateResultVO; import com.central.device.model.vo.RouteValidateResultVO;
import java.time.LocalDateTime;
import java.util.List; import java.util.List;
/** /**
@@ -69,6 +70,20 @@ public interface IBoatRouteService extends IService<BoatRoute> {
*/ */
Page<BoatRouteListVO> listByScenicId(Long scenicId, Integer page, Integer size); Page<BoatRouteListVO> listByScenicId(Long scenicId, Integer page, Integer size);
/**
* 分页查询无人船航线列表
*
* @param routeName 航线名称
* @param deviceSn 设备SN
* @param startTime 创建开始时间
* @param endTime 创建结束时间
* @param page 页码
* @param size 每页数量
* @return 航线分页列表
*/
Page<BoatRouteListVO> pageRoutes(String routeName, String deviceSn, LocalDateTime startTime, LocalDateTime endTime,
Integer page, Integer size);
/** /**
* 绑定航线到设备 * 绑定航线到设备
* *
@@ -6,6 +6,7 @@ import com.central.device.boat.entity.BoatRoute;
import com.central.device.boat.manager.BoatCommandManager; import com.central.device.boat.manager.BoatCommandManager;
import com.central.device.model.AgeDevice; import com.central.device.model.AgeDevice;
import com.central.device.model.dto.BoatManualControlDTO; import com.central.device.model.dto.BoatManualControlDTO;
import com.central.device.model.dto.BoatSlowlyDriveDTO;
import com.central.device.service.IAgeDeviceService; import com.central.device.service.IAgeDeviceService;
import com.central.device.service.IBoatControlService; import com.central.device.service.IBoatControlService;
import com.central.device.service.IBoatRouteService; import com.central.device.service.IBoatRouteService;
@@ -86,6 +87,18 @@ public class BoatControlServiceImpl implements IBoatControlService {
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", params); boatCommandManager.sendCommand(deviceSn, "flighttask_undo", params);
} }
@Override
public void slowly(String deviceSn, BoatSlowlyDriveDTO dto) {
log.info("无人船慢速行驶: deviceSn={}, missionCode={}, speed={}",
deviceSn, dto.getMissionCode(), dto.getSpeed());
JSONObject params = new JSONObject();
params.put("order_no", dto.getMissionCode());
params.put("speed", dto.getSpeed());
boatCommandManager.sendCommand(deviceSn, "flighttask_slowly", params);
}
@Override @Override
public void returnToStart(String deviceSn) { public void returnToStart(String deviceSn) {
log.info("无人船返回起点: deviceSn={}", deviceSn); log.info("无人船返回起点: deviceSn={}", deviceSn);
@@ -35,6 +35,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@@ -314,6 +315,34 @@ public class BoatRouteServiceImpl extends ServiceImpl<BoatRouteMapper, BoatRoute
return resultPage; return resultPage;
} }
@Override
public Page<BoatRouteListVO> pageRoutes(String routeName, String deviceSn, LocalDateTime startTime,
LocalDateTime endTime, Integer page, Integer size) {
String anchor = LoginUserContextHolder.getCurrentTenantId();
try {
if (anchor == null || anchor.isEmpty()) {
anchor = com.central.common.context.TenantQueryOverrideContext.getTenantId();
}
} catch (Exception ignored) {
log.error("获取当前登录用户租户失败");
}
Page<BoatRoute> pageParam = new Page<>(page, size);
LambdaQueryWrapper<BoatRoute> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(anchor != null && !anchor.isEmpty(), BoatRoute::getTenantId, anchor)
.eq(BoatRoute::getDeleted, 0)
.like(StrUtil.isNotBlank(routeName), BoatRoute::getRouteName, StrUtil.trim(routeName))
.like(StrUtil.isNotBlank(deviceSn), BoatRoute::getDeviceSn, StrUtil.trim(deviceSn))
.ge(startTime != null, BoatRoute::getCreateTime, startTime)
.le(endTime != null, BoatRoute::getCreateTime, endTime)
.orderByDesc(BoatRoute::getCreateTime);
Page<BoatRoute> routePage = this.page(pageParam, wrapper);
Page<BoatRouteListVO> resultPage = new Page<>(page, size, routePage.getTotal());
resultPage.setRecords(convertToListVO(routePage.getRecords()));
return resultPage;
}
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void bindToDevice(String routeId, String deviceSn) { public void bindToDevice(String routeId, String deviceSn) {
@@ -147,8 +147,7 @@ public class DeviceCommandManager {
parameter.put("properties", properties); parameter.put("properties", properties);
JSONObject headers = new JSONObject(); JSONObject headers = new JSONObject();
// 指点飞行的下发、更新和停止均由设备异步执行,其余命令维持原有同步应答语义。 headers.put("async", false);
headers.put("async", requiresAsyncHeader(command.getCommandType()));
parameter.put("headers", headers); parameter.put("headers", headers);
// 构造完整消息 // 构造完整消息
@@ -268,43 +267,6 @@ public class DeviceCommandManager {
data.put("locked", params.getBooleanValue("locked")); data.put("locked", params.getBooleanValue("locked"));
break; break;
case "live_lens_change":
// 切换直播镜头
data.put("video_type", params.getString("video_type"));
break;
case "camera_focal_length_set":
// 设置变焦倍数
data.put("camera_type", params.getString("camera_type"));
data.put("zoom_factor", params.getDoubleValue("zoom_factor"));
break;
case "fly_to_point":
// 首次飞向目标点(生成 fly_to_id 会话)
data.put("fly_to_id", params.getString("fly_to_id"));
data.put("max_speed", params.getFloatValue("max_speed"));
// points 数组
JSONObject pointFirst = new JSONObject();
pointFirst.put("height", params.getFloatValue("height"));
pointFirst.put("latitude", params.getDoubleValue("latitude"));
pointFirst.put("longitude", params.getDoubleValue("longitude"));
data.put("points", new JSONObject[]{pointFirst});
break;
case "fly_to_point_update":
// 更新目标点(设备协议无 fly_to_id,仅 max_speed + points)
data.put("max_speed", params.getFloatValue("max_speed"));
JSONObject pointUpdate = new JSONObject();
pointUpdate.put("height", params.getFloatValue("height"));
pointUpdate.put("latitude", params.getDoubleValue("latitude"));
pointUpdate.put("longitude", params.getDoubleValue("longitude"));
data.put("points", new JSONObject[]{pointUpdate});
break;
case "fly_to_point_stop":
// 停止指点飞行 - 无参数
break;
default: default:
// 其他命令,直接使用 params 作为 data // 其他命令,直接使用 params 作为 data
data = params; data = params;
@@ -313,8 +275,8 @@ public class DeviceCommandManager {
properties.put("method", method); properties.put("method", method);
// 设备协议要求任务型飞行命令使用 data.data 嵌套结构。 // 一键起飞命令需要 data.data 的嵌套结构,其他命令直接使用 data
if (requiresNestedDataWrapper(method)) { if ("takeoff_to_point".equals(method)) {
JSONObject dataWrapper = new JSONObject(); JSONObject dataWrapper = new JSONObject();
dataWrapper.put("data", data); dataWrapper.put("data", data);
properties.put("data", dataWrapper); properties.put("data", dataWrapper);
@@ -325,18 +287,6 @@ public class DeviceCommandManager {
return properties; return properties;
} }
private boolean requiresNestedDataWrapper(String method) {
return "takeoff_to_point".equals(method)
|| "fly_to_point".equals(method)
|| "fly_to_point_update".equals(method);
}
private boolean requiresAsyncHeader(String method) {
return "fly_to_point".equals(method)
|| "fly_to_point_update".equals(method)
|| "fly_to_point_stop".equals(method);
}
/** /**
* 加入队列 * 加入队列
*/ */
@@ -449,120 +399,11 @@ public class DeviceCommandManager {
}, delay, TimeUnit.MILLISECONDS); }, delay, TimeUnit.MILLISECONDS);
} }
/**
* 同步等待的命令 Future 缓存: commandId -> CompletableFuture
*/
private final ConcurrentHashMap<String, CompletableFuture<CommandResult>> syncFutures = new ConcurrentHashMap<>();
/**
* 发送命令并同步等待设备响应
* 实现要点:先生成 commandId → 注册 Future → 再发送命令(避免设备快速响应时 Future 未注册的竞态)
*
* @param deviceSn 设备SN
* @param commandType 命令类型
* @param params 命令参数
* @param timeoutMs 超时时间(毫秒)
* @return 命令结果
*/
public CommandResult sendCommandSync(String deviceSn, String commandType, JSONObject params, long timeoutMs) {
// 1. 先生成 commandId
String commandId = UUID.randomUUID().toString();
// 2. 创建 Future 并注册(必须在发送命令之前)
CompletableFuture<CommandResult> future = new CompletableFuture<>();
syncFutures.put(commandId, future);
// 3. 创建命令对象并发送
DeviceCommand command = DeviceCommand.builder()
.commandId(commandId)
.deviceSn(deviceSn)
.commandType(commandType)
.params(params != null ? params : new JSONObject())
.status(CommandStatus.PENDING)
.createTime(System.currentTimeMillis())
.sendTime(0)
.expireTime(System.currentTimeMillis() + timeoutMs)
.retryCount(0)
.maxRetry(0)
.build();
log.info("创建同步命令: commandId={}, device={}, type={}, timeout={}ms",
commandId, deviceSn, commandType, timeoutMs);
try {
// 4. 检查并发送
if (!jetLinksWebSocketClient.isConnected()) {
jetLinksWebSocketClient.connect();
int waitCount = 0;
while (!jetLinksWebSocketClient.isConnected() && waitCount < 50) {
Thread.sleep(100);
waitCount++;
}
}
if (jetLinksWebSocketClient.isConnected()) {
sendCommandImmediately(command);
} else {
syncFutures.remove(commandId);
return CommandResult.failed("WebSocket 未连接");
}
// 5. 阻塞等待结果
CommandResult result = future.get(timeoutMs, TimeUnit.MILLISECONDS);
log.info("同步命令完成: commandId={}, success={}", commandId, result.isSuccess());
return result;
} catch (TimeoutException e) {
log.error("同步命令超时: commandId={}, device={}, type={}, timeout={}ms",
commandId, deviceSn, commandType, timeoutMs);
syncFutures.remove(commandId);
return CommandResult.timeout("命令执行超时");
} catch (Exception e) {
log.error("同步命令异常: commandId={}, error={}", commandId, e.getMessage());
syncFutures.remove(commandId);
return CommandResult.failed("命令执行异常: " + e.getMessage());
}
}
/**
* 命令结果 DTO
*/
@lombok.Data
@lombok.AllArgsConstructor
public static class CommandResult {
private boolean success;
private String message;
private String commandId;
public static CommandResult success(String commandId) {
return new CommandResult(true, "执行成功", commandId);
}
public static CommandResult failed(String message) {
return new CommandResult(false, message, null);
}
public static CommandResult timeout(String message) {
return new CommandResult(false, message, null);
}
}
/** /**
* 接收设备命令响应 * 接收设备命令响应
*/ */
public void handleCommandResponse(String commandId, boolean success, String message) { public void handleCommandResponse(String commandId, boolean success, String message) {
DeviceCommand command = pendingCommands.remove(commandId); DeviceCommand command = pendingCommands.remove(commandId);
// 同步等待的 Future 回调
CompletableFuture<CommandResult> syncFuture = syncFutures.remove(commandId);
if (syncFuture != null) {
if (success) {
syncFuture.complete(CommandResult.success(commandId));
} else {
syncFuture.complete(CommandResult.failed(message != null ? message : "设备执行失败"));
}
}
if (command == null) { if (command == null) {
log.warn("收到未知命令响应: commandId={}", commandId); log.warn("收到未知命令响应: commandId={}", commandId);
return; return;
@@ -612,11 +453,6 @@ public class DeviceCommandManager {
command.setStatus(CommandStatus.TIMEOUT); command.setStatus(CommandStatus.TIMEOUT);
log.warn("命令响应超时: commandId={}, device={}", log.warn("命令响应超时: commandId={}, device={}",
command.getCommandId(), command.getDeviceSn()); command.getCommandId(), command.getDeviceSn());
// 同步 Future 超时回调
CompletableFuture<CommandResult> syncFuture = syncFutures.remove(command.getCommandId());
if (syncFuture != null) {
syncFuture.complete(CommandResult.timeout("命令响应超时"));
}
pendingTimeoutCount.incrementAndGet(); pendingTimeoutCount.incrementAndGet();
return true; return true;
} }
@@ -1,770 +0,0 @@
# JetLinks WebSocket 对接方案 — 迁移指南
> 目标读者:把这套 JetLinks 平台对接方案迁移到新 Spring Boot 项目的开发者。
> 覆盖范围:WebSocket 长连接 + 主题订阅 + 命令下发 + 分布式引用计数 + 消息解析全流程。
---
## 一、方案能力
- **单节点单连接**:全局共享一条 WebSocket,所有设备走主题订阅模式。
- **懒加载**:项目启动不连接,首次订阅或首次发命令时才建立连接;全部取消后自动断开。
- **分布式安全**:多实例通过 Redis 引用计数决定首/末订阅者,跨实例互不干扰。
- **自动重连 + Token 自刷新**:指数退避重连;`authError` 触发 Token 刷新后再重连;重连后基于 Redis 状态挑选真实需要的主题。
- **命令队列**:断线时命令进队列,重连后按顺序重发;支持指数退避重试、超时清理、异步 response 回调。
- **多产品线兼容**:默认适配大疆机场(AutoDock3),改主题模板即可支持其他产品。
---
## 二、整体架构
```
┌────────────────────────────────────────────────────────┐
│ 业务入口(SSE / REST / MQ 消费者 …) │
└────────────────────────┬───────────────────────────────┘
↓
┌────────────────────────────────────────────────────────┐
│ SubscriptionPoolService(Redis 引用计数,分布式共享) │
│ device:sub:{sn}:{topicType} → Set<sessionId> │
│ device:sub:session:{sessionId} → Set<sn:topicType> │
└────────────────────────┬───────────────────────────────┘
首/末订阅者触发或取消
↓
┌────────────────────────────────────────────────────────┐
│ DeviceSubscriptionManager(业务侧订阅编排) │
└────────────────────────┬───────────────────────────────┘
↓
┌────────────────────────────────────────────────────────┐
│ JetLinksWebSocketClient(全局单例长连接) │
│ - subscribedTopics / topicSubscriptionIds │
│ - deviceSubscriptionCounts │
│ - 心跳 / 重连 / 认证过期 → 刷新Token │
└────────┬──────────────────────────────┬────────────────┘
↓ ↓
┌──────────────────┐ ┌──────────────────────┐
│ TokenManager │ │ DeviceMessageHandler │
│ OAuth2 + 缓存 │ │ 解析 / 缓存 / 推送 │
└──────────────────┘ └──────────┬───────────┘
↓
┌──────────────────────┐
│ DeviceCommandManager │
│ 命令队列 / 重试 / 超时 │
└──────────────────────┘
可选:IsolatedWebSocketClient —— 一次性抓取场景独立短连接
```
---
## 三、依赖与配置
### 3.1 Maven 依赖
```xml
<!-- Spring 基础 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- OAuth2 Token 获取 -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
<!-- JSON 处理 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.53</version>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
```
Spring Boot 3.x 使用 `jakarta.annotation.*`;Spring Boot 2.x 需改为 `javax.annotation.*`。
### 3.2 application.yml
```yaml
device:
websocket:
oauth2:
token-url: http://<jetlinks-host>:8848/oauth2/token
client-id: <your-client-id>
client-secret: <your-client-secret>
connection:
base-url: ws://<jetlinks-host>:8848/device
connect-timeout: 10000
read-timeout: 60000
heartbeat:
enabled: true
interval: 30000
reconnect:
enabled: true
max-attempts: 10
initial-delay: 2000
max-delay: 60000
multiplier: 2
subscribe:
batch-size: 50
batch-interval: 500
on-demand: true
timeout:
offline-threshold: 60000
check-interval: 10000
command:
default-timeout: 60000
max-retry: 3
retry-delay-base: 1000
queue-max-size: 100
cleanup-interval: 10000
spring:
redis:
host: <redis-host>
port: 6379
password: <optional>
```
### 3.3 启动类
```java
@SpringBootApplication
@EnableScheduling // 命令过期清理需要
public class YourApp { ... }
```
---
## 四、文件清单(14 个 Java 文件)
放到你的项目里,保留同名包结构;`com.central.device.websocket` 可整体改成你项目的包名。
```
websocket/
├── config/
│ └── WebSocketProperties.java
├── client/
│ ├── JetLinksWebSocketClient.java ★ 核心
│ └── IsolatedWebSocketClient.java (可选)
├── manager/
│ ├── TokenManager.java
│ ├── SubscriptionPoolService.java
│ ├── DeviceSubscriptionManager.java ★ 需按新项目改造
│ └── DeviceCommandManager.java
├── handler/
│ └── DeviceMessageHandler.java ★ 需按新项目改造
└── model/
├── SubscriptionTopic.java ★ 需按产品线改
├── SubscriptionMessage.java
├── DeviceCommand.java
├── CommandStatus.java
├── DeviceRealtimeData.java
├── DroneRealtimeData.java
├── GpsData.java
└── message/
├── PropertyReportMessage.java
├── DeviceStateEventMessage.java
└── MsgAlarmEventMessage.java
```
---
## 五、协议参考(JetLinks 侧)
### 5.1 主题订阅报文
```json
// 订阅
{"type":"sub","topic":"/device/AutoDock3/{sn}/message/event/fire_alarm","parameter":{},"id":"sub-xxx"}
// 取消订阅 (id 必须与订阅时相同)
{"type":"unsub","topic":"/device/AutoDock3/{sn}/message/event/fire_alarm","parameter":{},"id":"sub-xxx"}
// 心跳
{"type":"ping","timestamp":1700000000000}
// 服务端回复
{"type":"pong"}
// 认证过期
{"type":"authError","message":"..."}
```
### 5.2 命令下发报文
```json
{
"type": "sub",
"topic": "/device-message-sender/AutoDock3/{sn}",
"parameter": {
"messageType": "WRITE_PROPERTY",
"properties": {
"method": "takeoff_to_point",
"data": { "data": { /* 指令参数 */ } }
},
"headers": { "async": false }
},
"id": "request-id-xxx"
}
```
### 5.3 主题列表(大疆机场默认)
| 主题模板 | 说明 |
|---------|------|
| `/device/AutoDock3/{sn}/online` | 设备上线 |
| `/device/AutoDock3/{sn}/offline` | 设备离线 |
| `/device/AutoDock3/{sn}/message/property/report` | 属性上报 |
| `/device/AutoDock3/{sn}/message/event/fire_alarm` | **设备状态事件**(非火警,是机库/无人机综合状态) |
| `/device/AutoDock3/{sn}/message/event/msg_alarm` | 无人机遥测数据 |
| `/device-message-sender/AutoDock3/{sn}` | 命令下发 / 命令响应 |
新项目若接不同产品线,改 `SubscriptionTopic` 里的模板段(例如 `D-Dock2`、`ship`)或用 `subscribeRawTopic()` 传入完整 topic。
### 5.4 大疆 DRC 指令集
按 `method` 分类,`DeviceCommandManager.buildCommandProperties()` 已按指令组装好参数:
| method | 参数 | 说明 |
|--------|------|------|
| `takeoff_to_point` | 经纬度、目标高度、返航高度等 | 一键起飞(注意 `data.data` 嵌套) |
| `return_home` / `return_home_cancel` | 无 | 一键返航 / 取消返航 |
| `flighttask_pause` / `flighttask_recovery` | 无 | 航线暂停 / 恢复 |
| `drc_mode_enter` | 无 | 进入指令飞行模式 |
| `stick_control` | roll/pitch/throttle/yaw (624~1424) | DRC 杆量控制,5-10Hz 下发 |
| `camera_screen_drag` | pitch_speed / yaw_speed / locked | 云台拖动 |
| `camera_mode_switch` | camera_mode (0拍照/1录像/2低光/3全景) | 切相机模式 |
| `camera_photo_take` | 无 | 拍照 |
| `camera_recording_start` / `camera_recording_stop` | 无 | 录像开始 / 结束 |
---
## 六、关键设计要点(迁移时必须理解)
### 6.1 懒加载 + 自动断开
```java
// JetLinksWebSocketClient.subscribeDevice()
if (!isConnected()) {
connect(); // 首次触发连接
// 最多等 5 秒
while (!isConnected() && waitCount < 50) { Thread.sleep(100); waitCount++; }
}
// ...
// unsubscribeDevice() 末尾
if (subscribedTopics.isEmpty()) {
deviceSubscriptionCounts.clear();
closeConnection(); // 全部取消 → 主动断开
}
```
`closeConnection()` 会置 `isAutoClose=true`,`afterConnectionClosed()` 里跳过重连。
### 6.2 订阅 ID 一致性(重要)
订阅和取消订阅必须携带同一个 `id`,否则 JetLinks 无法定位该订阅。用 `topicSubscriptionIds` 保存 `topic → id` 的映射:
```java
String subscriptionId = "sub-" + deviceSn + "-" + topic + "-" + UUID.randomUUID().toString().substring(0, 8);
topicSubscriptionIds.put(topic, subscriptionId);
// 发订阅报文...
// 取消时:
String subscriptionId = topicSubscriptionIds.remove(topic);
// 发取消订阅报文,携带相同 id
```
### 6.3 Redis 双向索引 + 引用计数
```
device:sub:{sn}:{topicType} → Set<sessionId> # 按设备主题反查订阅者
device:sub:session:{sessionId} → Set<sn:topicType> # 按 session 快速清理
```
- `addSubscription()` → SADD 到两个 Set,返回是否是**首次订阅者**(`isFirst`),只有 true 才向 WebSocket 发订阅报文。
- `removeSubscription()` → SREM,返回是否是**最后一个订阅者**(`isLast`),只有 true 才发取消订阅报文。
- 24h TTL 兜底 + 60s 一次孤儿清理(活跃 sessionId 集合 vs Redis 中的 session)。
**分布式必备**。单机也建议用同一套代码,切换到嵌入式 Redis 或删掉分布式逻辑都可以。
### 6.4 消息路由
```
handleTextMessage()
├── type=pong → 忽略
├── type=authError → 刷 Token + 重连
├── topic 含 /device-message-sender/ → 命令响应 → DeviceCommandManager
└── 其他 → handleSubscriptionResult()
├── /online → markDeviceOnline
├── /offline → markDeviceOffline
├── /message/property/report → handlePropertyReport
├── /message/event/fire_alarm → handleDeviceStateEvent
└── /message/event/msg_alarm → handleMsgAlarmEvent
```
从 topic 提取 deviceSn 的规则:`/device/{productType}/{sn}/...` 或 `/device-message-sender/{productType}/{sn}` 的第 4 段。
### 6.5 fire_alarm 三段合并(大疆机场特性)
`fire_alarm` 会循环推送三种结构的数据:
| 类型 | 识别字段 | 内容 |
|-----|---------|------|
| 0 - 飞行任务 | `wireless_link` / `sdr` / `tilt_angle` / `flighttask_step_code` | 图传状态 |
| 1 - 机库综合 | `drone_charge_state` / `sub_device` / `environment_temperature` | 环境+子设备 |
| 2 - 机库状态 | `drone_battery_maintenance_info` / `electric_supply_voltage` | 供电+电池 |
`DeviceMessageHandler.deviceDataCache[sn] = JSONObject[3]`,按 `identifyDataType()` 归位;**三种齐全**才 `deepMerge()` 并向下游推送,避免半截数据。
### 6.6 心跳 & 重连
- 心跳:默认 30s,发 `{"type":"ping","timestamp":...}`。
- 重连:指数退避,`delay = min(initialDelay × multiplier^attempts, maxDelay)`。
- 重连成功后 `resubscribeAll()`:**基于 Redis 池状态**决定订阅哪些主题(避免恢复已取消的死订阅):
```java
if (subscriptionPoolService.hasSubscribers(sn, TopicType.FIRE_ALARM)) topics.add(EVENT_FIRE_ALARM);
if (subscriptionPoolService.hasSubscribers(sn, TopicType.MSG_ALARM)) topics.add(EVENT_MSG_ALARM);
if (hasFireAlarm || hasMsgAlarm || hasOnline) topics.add(ONLINE);
if (hasFireAlarm || hasMsgAlarm || hasOffline) topics.add(OFFLINE);
```
### 6.7 Token 生命周期
- OAuth2 `client_credentials` 模式,`expires_in - 60s` 判过期。
- 3 次重试;重试全部失败时,如果旧 token 距离真实过期还有 60s 缓冲,允许降级返回旧 token。
- 收到 `authError` 时刷新 Token → 关连接 → 触发重连。
### 6.8 命令下发流程
```
sendCommand(sn, method, params)
↓
未连接?→ connect() + 最多等 5s
↓
连接成功 → sendCommandImmediately()
↓ (放入 pendingCommands 等待响应)
连接失败 → addToQueue()(每设备独立队列,上限 100)
↓
【收到响应】/device-message-sender/... → handleCommandResponse(commandId, success, msg)
【WS 重连】 → onWebSocketReconnected() → 按队列顺序重发(每条间隔 100ms)
【超时】@Scheduled 每 10s 扫描 → 队列过期 EXPIRED / pendingCommands 超时 TIMEOUT
【发送异常】retryCommand() 指数退避重试 (delay = 2^retryCount × base)
```
### 6.9 抑制无效日志
- `subscribedTopics.contains(topic)` 过滤已取消订阅但延迟到达的消息。
- `recentlyUnsubscribedDevices` 5s 宽限期,避免 unsubscribe 瞬间刷 warn。
---
## 七、迁移改造清单
### 7.1 必须适配的 4 处
**1. 产品类型(`SubscriptionTopic.java`)**
```java
// 默认全是 AutoDock3,改成你的产品:
ONLINE("/device/AutoDock3/{deviceSn}/online"),
// →
ONLINE("/device/YourProduct/{deviceSn}/online"),
```
**2. 命令 topic 前缀(`DeviceCommandManager.sendCommandImmediately`)**
```java
message.put("topic", "/device-message-sender/AutoDock3/" + command.getDeviceSn());
// → 改成你的产品
```
**3. 业务耦合点(`DeviceSubscriptionManager`)**
原代码依赖 `IAgeDeviceService`(景区设备表)和 `DeviceMessageHandler.addDevice(sn, scenicId, tenantId)`。迁移时二选一:
- 保留景区级订阅:用你项目的设备 Service 替换 `IAgeDeviceService`。
- 只要单设备订阅:删掉 `subscribeForScenic` / `unsubscribeForScenic` / 景区缓存,只保留下面这个方法:
```java
public void subscribeDevice(String deviceSn, String tenantId) {
messageHandler.addDevice(deviceSn, 0L, tenantId);
jetLinksWebSocketClient.subscribeDevice(deviceSn,
SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE, SubscriptionTopic.EVENT_FIRE_ALARM);
}
public void unsubscribeDevice(String deviceSn) {
// ⚠️ 不要取消 EVENT_MSG_ALARM,那是操控台单独管理的
jetLinksWebSocketClient.unsubscribeDevice(deviceSn,
SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE, SubscriptionTopic.EVENT_FIRE_ALARM);
messageHandler.removeDevice(deviceSn);
}
```
**4. 下游推送(`DeviceMessageHandler.pushDeviceDataUpdate`)**
原代码通过反射调用 `sseEmitterManager.sendDeviceDataUpdate(sn, data)` / `sendDroneDataUpdate(sn, data)`。新项目:
- 若继续用 SSE:实现同名方法,或直接把反射调用改成强类型调用。
- 换成 WebFlux Sink / MQ / 直接落库:改 `pushDeviceDataUpdate()` 和 `handleMsgAlarmEvent()` 里对应位置。
`DeviceAlarmDataService` 是把 fire_alarm / msg_alarm 快照写 Redis 的服务,可选实现。
### 7.2 依赖注入接线(有循环依赖)
`JetLinksWebSocketClient` ↔ `DeviceCommandManager` ↔ `SubscriptionPoolService` 三者有环,用 setter 打破。**必须**在启动后完成以下接线,否则重连时无法基于 Redis 状态恢复订阅、命令响应无法回调:
```java
// DeviceCommandManager 的 @PostConstruct 里已做:
jetLinksWebSocketClient.setCommandManager(this);
// 你需要显式做:
@Component
class WebSocketWiring {
@Autowired JetLinksWebSocketClient client;
@Autowired SubscriptionPoolService pool;
@Autowired DeviceMessageHandler handler;
@Autowired(required = false) YourSseManager sse;
@PostConstruct
void wire() {
client.setSubscriptionPoolService(pool);
if (sse != null) handler.setSseEmitterManager(sse);
}
}
```
### 7.3 已知问题(迁移前顺手修)
原项目审计报告发现的 P0 问题(详见 `WebSocket订阅机制审计报告.md`),新项目建议直接按修复版写:
**问题 A:机库 SSE 断开时按主题分别判断 `isLast`,不要 `&&` 合并**
```java
// 错误写法:
if (isLastFireAlarm && isLastOnline && isLastOffline) {
deviceSubscriptionManager.unsubscribeDevice(deviceSn); // 混合场景永远进不来
}
// 正确写法:
if (isLastFireAlarm) {
jetLinksWebSocketClient.unsubscribeDevice(sn, SubscriptionTopic.EVENT_FIRE_ALARM);
}
if (isLastOnline && isLastOffline
&& !subscriptionPoolService.hasSubscribers(sn, TopicType.MSG_ALARM)) {
jetLinksWebSocketClient.unsubscribeDevice(sn, SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE);
}
```
**问题 B:`unsubscribeDevice()` 不要连 `EVENT_MSG_ALARM` 一起取消**
`msg_alarm` 属于操控台生命周期,应由 `unsubscribeDroneTelemetry()` 单独管理。
---
## 八、上手示例
### 8.1 基础订阅 / 取消订阅(业务代码)
```java
@RestController
@RequestMapping("/device")
public class DeviceController {
@Autowired JetLinksWebSocketClient wsClient;
@Autowired SubscriptionPoolService pool;
@Autowired DeviceSubscriptionManager subMgr;
@PostMapping("/monitor/{sn}")
public Result<?> startMonitor(@PathVariable String sn,
@RequestParam String sessionId,
@RequestParam String tenantId) {
// 引用计数:只有首次订阅者才真正下发订阅报文
boolean isFirst = pool.addSubscription(sessionId, sn, TopicType.FIRE_ALARM)
| pool.addSubscription(sessionId, sn, TopicType.ONLINE)
| pool.addSubscription(sessionId, sn, TopicType.OFFLINE);
if (isFirst) subMgr.subscribeDevice(sn, tenantId);
return Result.ok();
}
@DeleteMapping("/monitor/{sn}")
public Result<?> stopMonitor(@PathVariable String sn,
@RequestParam String sessionId) {
boolean isLastFireAlarm = pool.removeSubscription(sessionId, sn, TopicType.FIRE_ALARM);
boolean isLastOnline = pool.removeSubscription(sessionId, sn, TopicType.ONLINE);
boolean isLastOffline = pool.removeSubscription(sessionId, sn, TopicType.OFFLINE);
if (isLastFireAlarm) {
wsClient.unsubscribeDevice(sn, SubscriptionTopic.EVENT_FIRE_ALARM);
}
if (isLastOnline && isLastOffline
&& !pool.hasSubscribers(sn, TopicType.MSG_ALARM)) {
wsClient.unsubscribeDevice(sn, SubscriptionTopic.ONLINE, SubscriptionTopic.OFFLINE);
}
return Result.ok();
}
}
```
### 8.2 下发命令
```java
@Autowired DeviceCommandManager cmdMgr;
// 一键起飞
JSONObject params = new JSONObject();
params.put("target_latitude", 31.2120679);
params.put("target_longitude", 110.86967);
params.put("target_height", 322.63797);
params.put("security_takeoff_height", 50);
params.put("rth_mode", 1);
params.put("rth_altitude", 50);
params.put("rc_lost_action", 2);
params.put("commander_mode_lost_action", 1);
params.put("commander_flight_mode", 1);
params.put("commander_flight_height", 50);
params.put("flight_id", UUID.randomUUID().toString());
params.put("max_speed", 5);
params.put("flight_safety_advance_check", 0);
String commandId = cmdMgr.sendCommand(deviceSn, "takeoff_to_point", params);
// 拍照
cmdMgr.sendCommand(deviceSn, "camera_photo_take", new JSONObject());
// 查询状态
CommandStatus status = cmdMgr.getCommandStatus(commandId);
```
### 8.3 SSE + 断开清理
前端刷新/关闭页面时用 `navigator.sendBeacon()` 触发后端清理;后端定时(60s)扫描活跃 session 列表,用 `SubscriptionPoolService.cleanupOrphanSessions(activeIds)` 清理孤儿。
---
## 八点五、两种命令下发方式(WebSocket vs REST)
命令下发有两条路径可选,可以按场景混用:
| 维度 | WebSocket 通道(本方案) | JetLinks REST API |
|------|-----------------------|-------------------|
| 实现类 | `DeviceCommandManager` | 直接 HTTP 调用 JetLinks |
| 触发点 | 长连接已建立时最快 | 无需长连接,任何时候都能发 |
| 响应机制 | 异步,通过 `/device-message-sender/...` 主题回调 `handleCommandResponse()` | 同步,HTTP 返回体即结果 |
| 断线容错 | 有队列 + 重连后重发 | 请求当场失败,需业务方重试 |
| 状态查询 | `commandManager.getCommandStatus(commandId)` | 无状态跟踪,靠 HTTP 响应 |
| 高频指令(DRC 杆量 5-10Hz) | ✅ 更合适 | ❌ 每次都建 HTTP 连接,太重 |
| 一次性长任务(航线下发) | ⚪ 可用 | ✅ 更合适,直接拿结果 |
### 8.5.1 WebSocket 通道 — HTTP 接口封装
`DeviceCommandController` 是 `DeviceCommandManager` 的 HTTP 门面,前端/其他服务直接调 REST 即可,无需感知 WebSocket 存在。搬到新项目改一下包和 `Result` 类型就能用:
**通用发送 / 状态查询:**
```
POST /device/command/send
Body: { "deviceSn": "SN123", "commandType": "takeoff_to_point", "params": {...} }
Resp: { "code": 0, "data": "<commandId>" }
GET /device/command/status/{commandId}
Resp: { "commandId":"...", "status":"SENT", "statusDesc":"已发送,等待设备响应",
"deviceSn":"SN123", "commandType":"takeoff_to_point",
"createTime":..., "sendTime":..., "retryCount":0, "errorMsg":null }
```
**语义化端点(对前端更友好):**
| 接口 | 方法 | 参数 | 说明 |
|------|------|------|------|
| `POST /device/command/takeoff` | body: `TakeoffRequest` | 一键起飞(自带默认值填充) |
| `POST /device/command/return?deviceSn=` | query | 一键返航 |
| `POST /device/command/return/cancel?deviceSn=` | query | 取消返航 |
| `POST /device/command/pause?deviceSn=` | query | 航线暂停 / 紧急悬停 |
| `POST /device/command/resume?deviceSn=` | query | 航线恢复 |
| `POST /device/command/photo?deviceSn=` | query | 拍照 |
| `POST /device/command/recording/start?deviceSn=` | query | 开始录像 |
| `POST /device/command/recording/stop?deviceSn=` | query | 停止录像 |
| `POST /device/command/camera/mode?deviceSn=&cameraMode=` | query | 切换相机模式 |
| `POST /device/command/drc/enter?deviceSn=` | query | 进入 DRC 模式 |
| `POST /device/command/drc/stick` | body: `StickControlRequest` | DRC 杆量控制 |
| `POST /device/command/gimbal` | body: `GimbalControlRequest` | 云台拖动控制 |
**调用示例(curl):**
```bash
# 拍照
curl -X POST 'http://<host>/device/command/photo?deviceSn=SN123'
# 一键起飞
curl -X POST 'http://<host>/device/command/takeoff' \
-H 'Content-Type: application/json' \
-d '{
"deviceSn": "SN123",
"targetLatitude": 31.2120679,
"targetLongitude": 110.86967,
"targetHeight": 322.6,
"commanderFlightHeight": 50,
"maxSpeed": 5
}'
# 查询命令执行状态
curl 'http://<host>/device/command/status/<commandId>'
```
**迁移改造清单:**
- `Result` / `@Tag` / `@Operation` 换成新项目对应的返回体和文档注解。
- `getStreamUrls(deviceSn)` 依赖本项目的设备表(推流地址),删掉或改成你项目的 Service。
- 起飞接口里 `flight_id` 默认取 UUID,业务上要联动订单号的话在这里改。
### 8.5.2 REST API 通道 — 直接调 JetLinks
JetLinks 平台自带一套设备属性下发 REST API,不需要 WebSocket 长连接。项目里"执行航线任务"就是走这条:
```
POST http://<jetlinks-host>:8848/device/instance/{deviceSn}/property
Header: Authorization: Bearer <token>
Body: { "method": "flighttask_prepare", "data": {...} }
Response: { "status": 200, "message": "success", "result": {...} }
错误码: 500 + "Device is offline" → 设备离线
```
**核心代码位置:** `DeviceCommandController.executeWayline()` 及其 `buildWaylineControlMessage()`。搬迁时需要一起带走的辅助类:
| 类 | 职责 |
|----|------|
| `RequestUtils` | 封装 `getPostRequestResult` 之类的 HTTP 调用(带鉴权头) |
| `IotRequestResult` | 解析 JetLinks 响应体 `{status, message, result}` |
| `ControlMessageConstant` | 保存指令模板 JSON(`flighttask_prepare`、`stick_control` 等) |
**REST 通道适用场景:**
- **航线任务下发**:payload 较大,一次性完成,需要立即知道结果。
- **属性读写**:与 `SubscriptionTopic.PROPERTY_READ / PROPERTY_WRITE` 等价,但同步返回。
- **无长连接的边缘节点/脚本**:只发一两条命令就退出,没必要建 WebSocket。
- **平台管理接口**:设备产品配置、日志查询、固件下发等 JetLinks 提供的 REST 能力。
**通用调用骨架(新项目可以直接抄):**
```java
@RestController
@RequestMapping("/device/rest-command")
public class DeviceRestCommandController {
@Value("${jetlinks.server.baseUrl}")
private String jetlinksBaseUrl;
@Autowired
private RequestUtils requestUtils; // 带 token 的 HTTP 调用工具
@PostMapping("/property/{deviceSn}")
public Result<String> sendProperty(@PathVariable String deviceSn,
@RequestBody JSONObject body) {
String url = jetlinksBaseUrl + "/device/instance/" + deviceSn + "/property";
Map<String, String> resp = requestUtils.getPostRequestResultMap(url, body.toJSONString());
JSONObject json = JSON.parseObject(resp.get(""));
IotRequestResult r = IotRequestResult.getInstance(json);
return r.getStatus() == 200
? Result.succeed(r.getMessage())
: Result.failed(r.getMessage());
}
}
```
`RequestUtils` 里需要注入 `TokenManager.getValidToken()` 作为 `Authorization: Bearer <token>` 头,Token 复用 WebSocket 通道那套 OAuth2 客户端凭证。
### 8.5.3 组合使用建议
| 场景 | 推荐通道 |
|------|---------|
| 前端页面持续订阅设备状态 | WebSocket |
| 高频控制指令(DRC 杆量、云台拖动) | WebSocket |
| 一次性拍照 / 录像开关 | 都可以,WebSocket 更省资源 |
| 航线下发、属性读写 | REST |
| 后台服务批量下发命令 | REST(无需维护长连接) |
| 无人值守脚本 / 定时任务 | REST |
**混合部署时的一致性:** 两条通道最终都到 JetLinks 平台,设备侧不区分来源。业务侧要注意命令幂等和状态跟踪 —— REST 通道没有 `commandId` 概念,需要业务方自己带任务号(如 `missionCode`)关联结果。
---
## 九、启动流程时序
```
1. Bean 装配
├── WebSocketProperties @ConfigurationProperties 装载
├── TokenManager 就绪(不请求 token)
├── JetLinksWebSocketClient.init() 只创建重连线程池
├── DeviceCommandManager.init() 回填 commandManager 引用
├── SubscriptionPoolService 就绪
└── WebSocketWiring.wire() setSubscriptionPoolService / setSseEmitterManager
2. 首次业务调用
├── 前端建立 SSE / 调 REST
├── SubscriptionPoolService.addSubscription() → isFirst=true
├── DeviceSubscriptionManager.subscribeDevice()
├── JetLinksWebSocketClient.subscribeDevice()
│ └── isConnected? → 否 → connect() → 等待 5s → afterConnectionEstablished()
│ ↓
│ startHeartbeat() + resubscribeAll()
└── 发订阅报文
```
---
## 十、监控与排障
**关键日志前缀:**
- `订阅设备:` / `取消订阅设备:` — 业务层订阅动作
- `发送订阅消息:` / `取消订阅主题:` — WebSocket 层实际报文
- `WebSocket连接成功` / `WebSocket连接关闭` — 连接状态
- `Token刷新成功` / `Token刷新失败` — Token 生命周期
- `命令发送成功` / `命令响应解析结果` — 命令流转
- `设备 X 数据未齐全` — fire_alarm 三段合并等待
**排障 checklist:**
- 收不到数据 → 确认 `subscribedTopics` 含目标 topic,`isConnected() == true`。
- 命令没响应 → 检查 topic 前缀(产品类型);检查 `pendingCommands` 是否有该 commandId。
- 重连后订阅错乱 → 确认 `setSubscriptionPoolService()` 已调用;查 `resubscribeAll()` 日志。
- Redis 池残留 → 手动跑 `SubscriptionPoolService.printSubscriptionStatus()` / `clearAllSubscriptions()`。
- 收到 `topic=null` warn → 通常是 `handleSubscriptionResult` 里的非设备消息(如订阅确认回执),不影响业务。
**订阅一致性巡检(推荐):**
```java
@Scheduled(fixedDelay = 300_000)
public void checkConsistency() {
for (String sn : wsClient.getActiveDevices()) {
int wsCount = wsClient.getDeviceSubscriptionCount(sn);
boolean redisHas = pool.hasSubscribers(sn, TopicType.FIRE_ALARM)
|| pool.hasSubscribers(sn, TopicType.MSG_ALARM)
|| pool.hasSubscribers(sn, TopicType.ONLINE);
if (wsCount > 0 && !redisHas) {
log.warn("检测到订阅残留: sn={}, wsCount={}", sn, wsCount);
}
}
}
```
---
## 十一、参考文档
同目录下的原始文档保留了更细节的部分,作为补充参考:
- `WebSocket懒加载使用说明.md` — 懒加载语义 + API 快速参考
- `WebSocket消息处理说明.md` — 消息 POJO 结构 + 处理逻辑
- `WebSocket订阅机制审计报告.md` — 已知问题 + 修复方案 + 场景推演
- `指令飞行.md` — 大疆 DRC 指令集完整参数字典
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,93 @@
{
"routeId": "33415e9578a74c59a16a5d2d3fee492c",
"routeName": "Manual Test Route 2026/4/6 16:16:59",
"deviceSn": "12345678",
"deviceName": "锦鲤一号",
"scenicId": 1,
"waypointCount": 5,
"totalDistance": 320.65,
"totalDuration": 1603,
"cruiseSpeed": 0.2,
"loopEnabled": false,
"loopCount": 1,
"returnMode": "origin",
"safeDistance": 5,
"startPoint": "121.89807344122099,30.87373280450406",
"endPoint": "121.8984168707936,30.873953677640834",
"status": 1,
"statusDesc": "Local Draft",
"waypoints": [
{
"waypointId": "289feeecdd554c3989759a584c777c09",
"waypointIndex": 0,
"longitude": 121.89807344122099,
"latitude": 30.87373280450406,
"speed": 2,
"stayDuration": 0,
"headingAngle": 49,
"turnMode": "smooth",
"isKeyPoint": false,
"pointName": "起点",
"actions": null,
"remark": null
},
{
"waypointId": "e1b7444d7d4942e2886b05f6b76f8392",
"waypointIndex": 1,
"longitude": 121.89865297403038,
"latitude": 30.874119329720497,
"speed": 2,
"stayDuration": 0,
"headingAngle": 49,
"turnMode": "smooth",
"isKeyPoint": false,
"pointName": "航点1",
"actions": null,
"remark": null
},
{
"waypointId": "ab214e90d4f6495d85abfeae791a6b53",
"waypointIndex": 2,
"longitude": 121.89949003611937,
"latitude": 30.874809529580364,
"speed": 2,
"stayDuration": 0,
"headingAngle": 49,
"turnMode": "smooth",
"isKeyPoint": false,
"pointName": "航点2",
"actions": null,
"remark": null
},
{
"waypointId": "e54c7b84314643538e9648d738a88ef7",
"waypointIndex": 3,
"longitude": 121.89906077613658,
"latitude": 30.874478239874847,
"speed": 2,
"stayDuration": 0,
"headingAngle": 233,
"turnMode": "smooth",
"isKeyPoint": false,
"pointName": "航点3",
"actions": null,
"remark": null
},
{
"waypointId": "2454526441a54e989fa4739c01510c18",
"waypointIndex": 4,
"longitude": 121.8984168707936,
"latitude": 30.873953677640834,
"speed": 2,
"stayDuration": 0,
"headingAngle": null,
"turnMode": "smooth",
"isKeyPoint": false,
"pointName": "终点",
"actions": null,
"remark": null
}
],
"createTime": "2026-04-06 08:16:59",
"updateTime": "2026-04-06 08:16:59"
}
@@ -78,6 +78,22 @@
} }
``` ```
### 2.5 慢速行驶(flighttask_slowly)
```json
{
"messageType": "WRITE_PROPERTY",
"deviceId": "12345678",
"properties": {
"data": {
"order_no": "562026040600002",
"speed": 30
},
"method": "flighttask_slowly"
}
}
```
## 三、架构设计原则 ## 三、架构设计原则
### 3.1 核心原则:不修改无人机代码,独立 boat 包 ### 3.1 核心原则:不修改无人机代码,独立 boat 包
@@ -169,9 +185,11 @@
| 文件 | 改动内容 | | 文件 | 改动内容 |
|------|----------| |------|----------|
| `ControlEnum.java` | 新增 `FLIGHTTASK_UNDO` 枚举值 | | `ControlEnum.java` | 新增 `FLIGHTTASK_UNDO` 枚举值 |
| `IBoatControlService.java` | `pause`/`resume` 增加 missionCode 参数;新增 `undoTask` 方法 | | `BoatCommandManager.java` | 新增 `flighttask_slowly` 指令组包逻辑,向设备透传 `order_no` 和 `speed` |
| `BoatControlServiceImpl.java` | **重写**:Mock 实现替换为通过 `BoatCommandManager` 发送真实 IoT 指令 | | `BoatSlowlyDriveDTO.java` | 新增慢速行驶请求模型,封装 `missionCode` 和 `speed` |
| `BoatCommandController.java` | pause/resume 接口增加 missionCode 参数;新增 undo 接口 | | `IBoatControlService.java` | `pause`/`resume` 增加 missionCode 参数;新增 `undoTask`、`slowly` 方法 |
| `BoatControlServiceImpl.java` | **重写**:Mock 实现替换为通过 `BoatCommandManager` 发送真实 IoT 指令;新增慢速行驶实现 |
| `BoatCommandController.java` | pause/resume 接口增加 missionCode 参数;新增 undo、slowly 接口 |
## 五、详细实现方案 ## 五、详细实现方案
@@ -279,6 +297,10 @@ public class BoatCommandManager {
case "flighttask_undo": case "flighttask_undo":
data.put("order_no", params.getString("order_no")); data.put("order_no", params.getString("order_no"));
break; break;
case "flighttask_slowly":
data.put("order_no", params.getString("order_no"));
data.put("speed", params.getInteger("speed"));
break;
default: default:
data = params; data = params;
break; break;
@@ -406,6 +428,7 @@ void resume(String deviceSn, String missionCode);
```java ```java
void undoTask(String deviceSn, String missionCode); void undoTask(String deviceSn, String missionCode);
void slowly(String deviceSn, BoatSlowlyDriveDTO dto);
``` ```
--- ---
@@ -463,6 +486,14 @@ public class BoatControlServiceImpl implements IBoatControlService {
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", params); boatCommandManager.sendCommand(deviceSn, "flighttask_undo", params);
} }
@Override
public void slowly(String deviceSn, BoatSlowlyDriveDTO dto) {
JSONObject params = new JSONObject();
params.put("order_no", dto.getMissionCode());
params.put("speed", dto.getSpeed());
boatCommandManager.sendCommand(deviceSn, "flighttask_slowly", params);
}
@Override @Override
public void returnToStart(String deviceSn) { public void returnToStart(String deviceSn) {
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", new JSONObject()); boatCommandManager.sendCommand(deviceSn, "flighttask_undo", new JSONObject());
@@ -512,6 +543,17 @@ public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String
} }
``` ```
#### 新增慢速行驶接口
```java
@PostMapping("/slowly")
public Result<Void> slowly(@RequestParam String deviceSn,
@RequestBody @Validated BoatSlowlyDriveDTO dto) {
boatControlService.slowly(deviceSn, dto);
return Result.succeed(null, "慢速行驶指令已下发");
}
```
--- ---
## 六、接口变更汇总 ## 六、接口变更汇总
@@ -521,6 +563,7 @@ public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String
| 方法 | 路径 | 参数 | 说明 | | 方法 | 路径 | 参数 | 说明 |
|------|------|------|------| |------|------|------|------|
| POST | `/device/boat/command/undo` | deviceSn, missionCode | 终止任务 | | POST | `/device/boat/command/undo` | deviceSn, missionCode | 终止任务 |
| POST | `/device/boat/command/slowly` | `deviceSn` + Body(`missionCode`,`speed`) | 下发慢速行驶指令 |
### 修改接口 ### 修改接口
@@ -549,6 +592,7 @@ public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String
| 1 | `boat/model/BoatSubscriptionTopic.java` | **新建** | 无人船订阅主题枚举 | | 1 | `boat/model/BoatSubscriptionTopic.java` | **新建** | 无人船订阅主题枚举 |
| 2 | `boat/manager/BoatCommandManager.java` | **新建** | 无人船命令管理器 | | 2 | `boat/manager/BoatCommandManager.java` | **新建** | 无人船命令管理器 |
| 3 | `boat/manager/BoatSubscriptionManager.java` | **新建** | 无人船订阅管理器 | | 3 | `boat/manager/BoatSubscriptionManager.java` | **新建** | 无人船订阅管理器 |
| 4 | `model/dto/BoatSlowlyDriveDTO.java` | **新建** | 无人船慢速行驶请求模型 |
## 八、修改文件清单 ## 八、修改文件清单
@@ -556,9 +600,10 @@ public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String
|---|---------|----------|------| |---|---------|----------|------|
| 1 | `websocket/client/JetLinksWebSocketClient.java` | 最小改动 | `extractDeviceSn()` 通用化(唯一共享改动) | | 1 | `websocket/client/JetLinksWebSocketClient.java` | 最小改动 | `extractDeviceSn()` 通用化(唯一共享改动) |
| 2 | `message/ControlEnum.java` | 追加 | 新增 `FLIGHTTASK_UNDO` 枚举值 | | 2 | `message/ControlEnum.java` | 追加 | 新增 `FLIGHTTASK_UNDO` 枚举值 |
| 3 | `service/IBoatControlService.java` | 修改 | 接口签名调整 + 新增方法 | | 3 | `boat/manager/BoatCommandManager.java` | 修改 | 新增 `flighttask_slowly` 组包逻辑 |
| 4 | `service/impl/BoatControlServiceImpl.java` | **重写** | Mock → 真实 IoT 指令下发 | | 4 | `service/IBoatControlService.java` | 修改 | 接口签名调整 + 新增 `slowly` 方法 |
| 5 | `controller/BoatCommandController.java` | 修改 | 接口参数调整 + 新增 undo | | 5 | `service/impl/BoatControlServiceImpl.java` | **重写** | Mock → 真实 IoT 指令下发,并新增慢速行驶实现 |
| 6 | `controller/BoatCommandController.java` | 修改 | 接口参数调整 + 新增 undo、slowly |
--- ---
@@ -600,10 +645,32 @@ public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String
} }
``` ```
### 无人船慢速行驶指令(新增)
```json
{
"type": "sub",
"topic": "/device-message-sender/ship/{deviceSn}",
"parameter": {
"messageType": "WRITE_PROPERTY",
"properties": {
"method": "flighttask_slowly",
"data": {
"order_no": "562026040600002",
"speed": 30
}
},
"headers": { "async": false }
},
"id": "{commandId}"
}
```
**区别**: **区别**:
1. topic 路径中产品标识不同:`AutoDock3` vs `ship` 1. topic 路径中产品标识不同:`AutoDock3` vs `ship`
2. 无人船的暂停/恢复/终止 data 中需要携带 `order_no` 2. 无人船的暂停/恢复/终止 data 中需要携带 `order_no`
3. 无人船的开始任务 data 中需要携带 `order_no`、`wayline_link_url`、`file_md5`、`stream_urls` 3. 无人船的开始任务 data 中需要携带 `order_no`、`wayline_link_url`、`file_md5`、`stream_urls`
4. 无人船的慢速行驶指令 data 中需要携带 `order_no`、`speed`
--- ---
@@ -689,3 +756,4 @@ data: ping
2. **返航/紧急停止指令**:目前映射到 `flighttask_undo`。如果无人船有专用的返航指令,后续需要替换。 2. **返航/紧急停止指令**:目前映射到 `flighttask_undo`。如果无人船有专用的返航指令,后续需要替换。
3. **手动控制协议**:`manualControl()` 方法暂保留接口,待后续提供手动控制协议后对接。 3. **手动控制协议**:`manualControl()` 方法暂保留接口,待后续提供手动控制协议后对接。
4. **设备在线状态/设备状态查询**:`isDeviceOnline()` 和 `getDeviceStatus()` 暂返回默认值,后续可对接 DeviceMessageHandler 中的实时数据。 4. **设备在线状态/设备状态查询**:`isDeviceOnline()` 和 `getDeviceStatus()` 暂返回默认值,后续可对接 DeviceMessageHandler 中的实时数据。
5. **慢速行驶速度的单位和范围**:当前按设备协议直接透传 `speed`,示例值为 `30`。如果设备端对单位、最小值、最大值有明确限制,需要继续补充参数校验。
@@ -1,92 +0,0 @@
package com.central.device.websocket.manager;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.central.device.websocket.model.CommandStatus;
import com.central.device.websocket.model.DeviceCommand;
import org.junit.Assert;
import org.junit.Test;
import java.lang.reflect.Method;
public class DeviceCommandManagerTest {
@Test
public void flyToPointUsesNestedDataWrapper() throws Exception {
JSONObject params = new JSONObject();
params.put("fly_to_id", "FP20260724164503");
params.put("max_speed", 12.0f);
params.put("height", 55.327644f);
params.put("latitude", 30.61043916027994d);
params.put("longitude", 114.39342878294764d);
JSONObject properties = buildProperties("fly_to_point", params);
Assert.assertEquals("fly_to_point", properties.getString("method"));
JSONObject outerData = properties.getJSONObject("data");
Assert.assertNotNull("指点飞行外层 data 下必须继续包含 data", outerData.getJSONObject("data"));
JSONObject commandData = outerData.getJSONObject("data");
Assert.assertEquals("FP20260724164503", commandData.getString("fly_to_id"));
Assert.assertEquals(12.0f, commandData.getFloatValue("max_speed"), 0.001f);
JSONArray points = commandData.getJSONArray("points");
Assert.assertEquals(1, points.size());
Assert.assertEquals(55.327644f, points.getJSONObject(0).getFloatValue("height"), 0.001f);
}
@Test
public void flyToPointUpdateUsesNestedDataWrapper() throws Exception {
JSONObject params = new JSONObject();
params.put("max_speed", 10.0f);
params.put("height", 60.0f);
params.put("latitude", 30.61043916027994d);
params.put("longitude", 114.39342878294764d);
JSONObject properties = buildProperties("fly_to_point_update", params);
JSONObject commandData = properties.getJSONObject("data").getJSONObject("data");
Assert.assertNotNull("连续指点更新也必须使用 data.data 包装", commandData);
Assert.assertEquals(10.0f, commandData.getFloatValue("max_speed"), 0.001f);
Assert.assertEquals(60.0f, commandData.getJSONArray("points").getJSONObject(0).getFloatValue("height"), 0.001f);
}
@Test
public void returnHomeKeepsFlatEmptyData() throws Exception {
JSONObject properties = buildProperties("return_home", new JSONObject());
Assert.assertEquals("return_home", properties.getString("method"));
JSONObject data = properties.getJSONObject("data");
Assert.assertNotNull(data);
Assert.assertFalse("返航命令不能新增 data.data 包装", data.containsKey("data"));
Assert.assertTrue(data.isEmpty());
}
@Test
public void flyToPointCommandsUseAsyncHeader() throws Exception {
Assert.assertTrue(requiresAsyncHeader("fly_to_point"));
Assert.assertTrue(requiresAsyncHeader("fly_to_point_update"));
Assert.assertTrue(requiresAsyncHeader("fly_to_point_stop"));
Assert.assertFalse(requiresAsyncHeader("return_home"));
}
private JSONObject buildProperties(String commandType, JSONObject params) throws Exception {
DeviceCommand command = DeviceCommand.builder()
.commandId("cmd-test")
.deviceSn("device-test")
.commandType(commandType)
.params(params)
.status(CommandStatus.PENDING)
.build();
DeviceCommandManager manager = new DeviceCommandManager();
Method method = DeviceCommandManager.class.getDeclaredMethod("buildCommandProperties", DeviceCommand.class);
method.setAccessible(true);
return (JSONObject) method.invoke(manager, command);
}
private boolean requiresAsyncHeader(String commandType) throws Exception {
DeviceCommandManager manager = new DeviceCommandManager();
Method method = DeviceCommandManager.class.getDeclaredMethod("requiresAsyncHeader", String.class);
method.setAccessible(true);
return (boolean) method.invoke(manager, commandType);
}
}
@@ -63,12 +63,6 @@ public class FileController {
@Value("${zlt.security.tencent.getwxacodeUrl}") @Value("${zlt.security.tencent.getwxacodeUrl}")
private String getwxacodeUrl; private String getwxacodeUrl;
@Value("${cdn.s3.domain:minicdn.goflytec.com}")
private String s3CdnDomain;
@Value("${cdn.s3.enabled:true}")
private boolean s3CdnEnabled;
private final RestTemplate restTemplate = new RestTemplate(); private final RestTemplate restTemplate = new RestTemplate();
@Value("${zlt.security.tencent.pagePath}") @Value("${zlt.security.tencent.pagePath}")
@@ -207,46 +201,6 @@ public class FileController {
return Result.succeed(map); return Result.succeed(map);
} }
/**
* 拉取外部图片 URL 字节并强制入 S3(不进 OSS / 不进智能路由)
* 用于支付宝小程序二维码:alipay.open.app.qrcode.create 返回临时 qr_code_url,需立刻拉回入 S3
*/
@GetMapping("/qrcode/s3/by-url")
public Result<Map> uploadQrCodeToS3ByUrl(@RequestParam("codeId") String codeId,
@RequestParam("qrUrl") String qrUrl,
@RequestParam(value = "suffix", required = false, defaultValue = "png") String suffix) throws Exception {
if (codeId == null || codeId.isEmpty() || qrUrl == null || qrUrl.isEmpty()) {
return Result.failed("codeId 和 qrUrl 不能为空");
}
ResponseEntity<byte[]> resp = restTemplate.exchange(qrUrl, HttpMethod.GET, HttpEntity.EMPTY, byte[].class);
if (!resp.getStatusCode().is2xxSuccessful() || resp.getBody() == null || resp.getBody().length == 0) {
return Result.failed("拉取二维码图片失败: " + resp.getStatusCode());
}
String fileName = codeId + "." + suffix;
FileInfo fileInfo = fileService.uploadForS3(fileName, new ByteArrayInputStream(resp.getBody()));
Map<String, Object> map = new LinkedHashMap<>();
map.put("codeId", codeId);
map.put("fileId", fileInfo.getId());
map.put("filePath", fileInfo.getPath());
return Result.succeed(map);
}
/**
* 直接 S3 无过期访问地址(绕过 TimeWindowStorageService 智能路由)
* 用于支付宝小程序二维码:与 AbstractIFileService.uploadForS3 上传时设置的 fileInfo.url 完全一致 ——
* 直接拼 https://<s3CdnDomain>/<objectPath>,不签名、不带过期、可被 CDN 缓存。
*/
@GetMapping("/files/s3/path")
public String getS3ViewUrlByPath(@RequestParam("path") String path) {
if (path == null || path.isEmpty()) {
return "";
}
if (s3CdnEnabled && s3CdnDomain != null && !s3CdnDomain.isEmpty()) {
return "https://" + s3CdnDomain + "/" + path;
}
return path;
}
@PostMapping("/path") @PostMapping("/path")
public FileInfo creatFileInfo(@RequestBody String path) { public FileInfo creatFileInfo(@RequestBody String path) {
return fileService.createFile(path); return fileService.createFile(path);
@@ -20,11 +20,6 @@ public interface IFileService extends IService<FileInfo> {
FileInfo uploadForS3(MultipartFile file ) throws Exception; FileInfo uploadForS3(MultipartFile file ) throws Exception;
/**
* 强制以 S3 方式上传字节流(用于支付宝小程序二维码等需绕开 OSS 的场景)
*/
FileInfo uploadForS3(String name, InputStream inputStream) throws Exception;
FileInfo upload(String name, InputStream inputStream) throws Exception; FileInfo upload(String name, InputStream inputStream) throws Exception;
PageResult<FileInfo> findList(Map<String, Object> params); PageResult<FileInfo> findList(Map<String, Object> params);
@@ -79,26 +79,6 @@ public abstract class AbstractIFileService extends ServiceImpl<FileMapper, FileI
return fileInfo; return fileInfo;
} }
@Override
public FileInfo uploadForS3(String name, InputStream inputStream) {
if (s3Template == null) {
throw new RuntimeException("S3服务未配置,无法使用S3上传");
}
FileInfo fileInfo = FileUtil.getFileInfo(name, inputStream);
if (!fileInfo.getName().contains(FILE_SPLIT)) {
throw new IllegalArgumentException("缺少后缀名");
}
ObjectInfo objectInfo = s3Template.upload(name, inputStream);
if (objectInfo == null) {
throw new RuntimeException("S3上传失败: " + name);
}
fileInfo.setPath(objectInfo.getObjectPath());
fileInfo.setUrl(buildCdnUrl(objectInfo.getObjectPath()));
fileInfo.setSource("s3");
baseMapper.insert(fileInfo);
return fileInfo;
}
/** /**
* 构建CDN URL * 构建CDN URL
* @param objectPath 对象路径 (格式: bucket/objectKey) * @param objectPath 对象路径 (格式: bucket/objectKey)
@@ -6,7 +6,6 @@ import com.aliyuncs.cdn.model.v20180510.*;
import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.DefaultProfile;
import com.central.file.config.CdnConfig; import com.central.file.config.CdnConfig;
import com.central.file.service.ICdnService; import com.central.file.service.ICdnService;
import com.central.file.utils.CdnUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -15,7 +14,6 @@ import org.springframework.util.CollectionUtils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/** /**
* CDN服务实现类 * CDN服务实现类
@@ -96,25 +94,9 @@ public class CdnServiceImpl implements ICdnService {
return null; return null;
} }
// 过滤掉视频文件:视频体积大且点播命中率低,预热会造成大量CDN回源流量
List<String> nonVideoUrls = urls.stream()
.filter(url -> {
if (CdnUtils.isVideoFile(url)) {
log.info("跳过视频文件预热: {}", url);
return false;
}
return true;
})
.collect(Collectors.toList());
if (nonVideoUrls.isEmpty()) {
log.info("过滤后无需要预热的文件(均为视频),跳过预热");
return null;
}
try { try {
PushObjectCacheRequest request = new PushObjectCacheRequest(); PushObjectCacheRequest request = new PushObjectCacheRequest();
request.setObjectPath(String.join("\n", nonVideoUrls)); request.setObjectPath(String.join("\n", urls));
if (area != null && !area.isEmpty()) { if (area != null && !area.isEmpty()) {
request.setArea(area); request.setArea(area);
} }
+6 -10
View File
@@ -90,6 +90,12 @@
<artifactId>hibernate-validator</artifactId> <artifactId>hibernate-validator</artifactId>
</dependency> </dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>compile</scope>
</dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId> <artifactId>spring-webflux</artifactId>
@@ -115,16 +121,6 @@
<artifactId>zlt-wechat-spring-boot-starter</artifactId> <artifactId>zlt-wechat-spring-boot-starter</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-alipay-common-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-alipay-spring-boot-starter</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies> </dependencies>
@@ -18,16 +18,6 @@ public class PayTypeConstants {
*/ */
public static final Integer COUPON_PAY = 2; public static final Integer COUPON_PAY = 2;
/**
* 第三方聚到核销
*/
public static final Integer FEIPAI_VERIFY = 3;
/**
* 支付宝支付
*/
public static final Integer ALIPAY_PAY = 4;
private PayTypeConstants() { private PayTypeConstants() {
// 私有构造函数,防止实例化 // 私有构造函数,防止实例化
} }
@@ -1,392 +0,0 @@
package com.central.order.controller;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.central.alipay.entity.AlipayConfig;
import com.central.alipay.notify.AlipayNotifyVerifier;
import com.central.alipay.service.AlipayPayService;
import com.central.alipay.service.AlipayRefundService;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.context.TenantContextHolder;
import com.central.common.feign.UserService;
import com.central.common.model.LoginAppUser;
import com.central.common.model.Result;
import com.central.common.model.SysUser;
import com.central.common.utils.SecurityTenantUtils;
import com.central.order.enums.OrderStatus;
import com.central.order.enums.PayTypeEnum;
import com.central.order.enums.RefundState;
import com.central.order.model.Order;
import com.central.order.model.QrCode;
import com.central.order.service.ICtripDistOrderService;
import com.central.order.service.IOrderService;
import com.central.order.service.IQrCodeService;
import com.central.order.service.IRefundService;
import com.central.order.service.IAlipayConfigService;
import com.central.order.util.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* 支付宝支付控制器(对标 WxPayController)
*
* @author duzhichao
* @date 2026-05-12
*/
@Slf4j
@RestController
@Tag(name = "支付宝支付管理", description = "支付宝小程序下单、支付/退款异步回调")
@RequestMapping("/alipay")
public class AliPayController {
@Autowired
private IOrderService orderService;
@Autowired
private IRefundService refundService;
@Autowired
private IQrCodeService qrCodeService;
@Autowired
private IAlipayConfigService alipayConfigService;
@Autowired
private AlipayPayService alipayPayService;
@Autowired
private AlipayRefundService alipayRefundService;
@Autowired
private AlipayNotifyVerifier alipayNotifyVerifier;
@Autowired
private ICtripDistOrderService ctripDistOrderService;
@Autowired
private UserService userService;
// ==================== 小程序下单 ====================
@Operation(summary = "支付宝小程序下单",
description = "调用 alipay.trade.create 获取 tradeNo,前端用 my.tradePay({tradeNo}) 拉起支付。"
+ "请求需携带 Authorization: Bearer <access_token>。"
+ "入参 JSON:orderId(必填)+buyerId(可选)。出参成功返回 { tradeNo, outTradeNo }")
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "{\"orderId\": 订单ID(必填), \"buyerId\": 支付宝userId(可选)}",
required = true,
content = @Content(schema = @Schema(example = "{\"orderId\": 1001, \"buyerId\": \"2088xxxxxxxxxxxx\"}")))
@PostMapping("/order/pay")
public Result<AlipayTradeCreateResponse> payOrder(@RequestBody Map<String, Object> body) {
Object rawOrderId = body.get("orderId");
Assert.notNull(rawOrderId, "orderId 不能为空");
Long orderId = Long.valueOf(rawOrderId.toString());
Order order = orderService.getById(orderId);
Assert.notNull(order, "订单不存在: " + orderId);
// 校验当前登录用户拥有该订单(防止替他人订单发起支付)
LoginAppUser currentUser = LoginUserContextHolder.getUser();
Assert.notNull(currentUser, "未登录或登录已过期");
if (order.getUserId() == null || !order.getUserId().equals(currentUser.getId())) {
throw new IllegalStateException("无权操作他人订单, orderId: " + orderId);
}
// 租户边界校验:订单租户必须与当前用户当前租户一致
String currentTenantId = SecurityTenantUtils.getCurrentTenantId();
if (currentTenantId != null && order.getTenantId() != null
&& !currentTenantId.equals(order.getTenantId())
&& !SecurityTenantUtils.isSuperAdmin()) {
throw new IllegalStateException("订单与当前租户不一致, orderId: " + orderId);
}
// 业务校验:订单必须为待支付状态,避免重复下单
if (!OrderStatus.UNPAID.getId().equals(order.getOrderStatus())) {
throw new IllegalStateException("订单状态不允许支付,orderId: " + orderId
+ ", status: " + order.getOrderStatus());
}
AlipayConfig config = alipayConfigService.getConfigByTypeAndTenantId("PAY", order.getTenantId());
Assert.notNull(config, "支付宝支付配置不存在,tenantId: " + order.getTenantId());
// buyerId 不信任前端传入:以服务端 sys_user_third_openid 映射为准
String buyerId = order.getUserId() != null
? userService.getAlipayOpenIdByUserId(order.getUserId(), config.getAppId())
: null;
Object rawBuyerId = body.get("buyerId");
if (rawBuyerId != null && !rawBuyerId.toString().isEmpty()) {
// 客户端传入 buyerId 时必须与服务端映射结果一致
if (buyerId == null || !buyerId.equals(rawBuyerId.toString())) {
throw new IllegalStateException("buyerId 与当前登录用户不匹配");
}
}
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
String subject = qrCode != null && qrCode.getName() != null
? qrCode.getName() : "景区订单-" + order.getOrderNo();
AlipayPayService.AlipayPayRequest req = new AlipayPayService.AlipayPayRequest();
req.setOutTradeNo(order.getOrderNo());
if (order.getOrderAmount() == null) {
throw new IllegalArgumentException("订单金额不能为空, orderId: " + orderId);
}
// Order.orderAmount 以"分"存储,支付宝 SDK total_amount 需要"元"
req.setTotalAmount(StringUtils.fenToYuanAmount(order.getOrderAmount()));
req.setSubject(subject);
req.setBuyerId(buyerId);
if (Boolean.TRUE.equals(config.getIsServiceMode()) && config.getSubMerchantId() != null) {
req.setSubMerchantId(config.getSubMerchantId());
}
AlipayTradeCreateResponse response = alipayPayService.create(config, req);
if (response.isSuccess()) {
return Result.succeed(response,order.getOrderNo());
} else {
return Result.failed(response.getMsg());
}
}
// ==================== 支付异步回调 ====================
@Operation(summary = "支付宝支付异步通知(支付宝服务器回调)",
description = "Content-Type: application/x-www-form-urlencoded。"
+ "支付宝以 POST form 方式回调,验签后更新订单状态为已支付。"
+ "关键入参:app_id、out_trade_no、trade_no、trade_status、total_amount、sign。"
+ "出参:纯文本 success 或 failure")
@PostMapping("/pay/notify")
public String handleAlipayPayNotify(HttpServletRequest request) {
Map<String, String> params = toMap(request);
log.info("------收到支付宝支付回调通知------, summary: {}", summarizeNotify(params));
try {
String appId = params.get("app_id");
// ISV(服务商)模式下应优先使用 auth_app_id 定位商家应用
String authAppId = params.get("auth_app_id");
String lookupAppId = (authAppId != null && !authAppId.isEmpty()) ? authAppId : appId;
AlipayConfig config = alipayConfigService.getConfigByAppIdAndType(lookupAppId, "PAY");
if (config == null) {
log.error("支付宝支付配置不存在,appId: {}, authAppId: {}", appId, authAppId);
return "failure";
}
TenantContextHolder.setTenant(config.getTenantId());
if (!alipayNotifyVerifier.verify(params, config)) {
log.warn("支付宝回调验签失败, summary:{}", summarizeNotify(params));
return "failure";
}
String tradeStatus = params.get("trade_status");
if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
handleAlipayPaymentResult(params, config);
} else {
log.info("支付宝支付回调忽略非成功状态: {}", tradeStatus);
}
return "success";
} catch (Exception e) {
// 关键步骤异常时返回 failure,触发支付宝重试(最多重试 8 次,间隔 2m/10m/10m/1h/2h/6h/15h)
log.error("处理支付宝支付回调失败,将由支付宝重试", e);
return "failure";
} finally {
TenantContextHolder.clear();
}
}
private void handleAlipayPaymentResult(Map<String, String> params, AlipayConfig config) {
String outTradeNo = params.get("out_trade_no");
String tradeNo = params.get("trade_no");
log.info("处理支付宝支付结果, 交易号:{}, 商户订单号:{}", tradeNo, outTradeNo);
Order order = orderService.getOrderByNumberWithFallback(outTradeNo, config.getTenantId());
if (order == null) {
// 订单不存在通常是数据落库延迟或脏数据,记录后让外层返回 failure 触发支付宝重试
log.error("支付宝回调订单不存在: {}, tenantId:{}", outTradeNo, config.getTenantId());
throw new IllegalStateException("订单不存在: " + outTradeNo);
}
if (OrderStatus.PAID.getId().equals(order.getOrderStatus())) {
log.info("订单已支付,跳过: {}", outTradeNo);
return;
}
// ===== 业务验真:避免回调被重放/金额不一致 =====
// 注意:租户一致性校验已移除,因为回调配置可能由 webApp 降级提供,
// 订单租户(如 hbzhapp)与配置租户(webApp)不一致属于正常场景。
// 安全性由以下校验保证:app_id 匹配 + 金额匹配 + seller_id 匹配
// 1) 金额一致:DB 以"分"存储,支付宝回调 total_amount 为"元"
String expectedYuan = StringUtils.fenToYuanAmount(order.getOrderAmount());
String notifyTotal = params.get("total_amount");
if (expectedYuan == null || notifyTotal == null
|| !expectedYuan.equals(notifyTotal.trim())) {
log.error("支付宝回调金额不一致, expected:{}, notify:{}, outTradeNo:{}",
expectedYuan, notifyTotal, outTradeNo);
throw new IllegalStateException("回调金额与订单金额不一致");
}
// 3) 应用身份一致:优先校验 auth_app_id(ISV),否则校验 app_id
String notifyAuthAppId = params.get("auth_app_id");
String notifyAppId = params.get("app_id");
String expectedAppId = config.getAppId();
if (notifyAuthAppId != null && !notifyAuthAppId.isEmpty()) {
if (!notifyAuthAppId.equals(expectedAppId)) {
log.error("支付宝回调 auth_app_id 不匹配配置, notify:{}, config:{}",
notifyAuthAppId, expectedAppId);
throw new IllegalStateException("回调应用身份不匹配");
}
} else if (notifyAppId == null || !notifyAppId.equals(expectedAppId)) {
log.error("支付宝回调 app_id 不匹配配置, notify:{}, config:{}", notifyAppId, expectedAppId);
throw new IllegalStateException("回调应用身份不匹配");
}
// 4) 商家身份(卖家)一致:ISV 模式下 seller_id 应等于配置的 PID;直连模式下 seller_id 等于配置 PID 也成立
String notifySellerId = params.get("seller_id");
if (config.getPid() != null && !config.getPid().isEmpty()
&& notifySellerId != null && !notifySellerId.isEmpty()
&& !config.getPid().equals(notifySellerId)) {
log.error("支付宝回调 seller_id 与配置 pid 不一致, notify:{}, configPid:{}",
notifySellerId, config.getPid());
throw new IllegalStateException("回调商家身份不匹配");
}
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
order.setOrderStatus(OrderStatus.PAID.getId());
order.setPayType(PayTypeEnum.ALIPAY_PAY.getCode());
order.setPayTime(new Date());
orderService.updateOrder(order);
// 携程分销订单为旁路异步任务,失败不影响本地订单完成
if (qrCode != null && Integer.valueOf(1).equals(qrCode.getEnableCtripOrder())) {
log.info("二维码已开启携程分销,异步创建携程订单,orderNo: {}", order.getOrderNo());
try {
String mobile = null;
if (Objects.nonNull(order.getUserId())) {
SysUser sysUser = userService.findUserById(order.getUserId());
if (Objects.nonNull(sysUser) && StringUtil.isNotEmpty(sysUser.getMobile())) {
mobile = sysUser.getMobile();
}
}
ctripDistOrderService.createCtripDistOrder(
order.getOrderNo(), order.getOrderAmount(),
qrCode.getCtripProductId(), order.getTenantId(), mobile);
} catch (Exception e) {
log.error("异步创建携程分销订单失败,orderNo: {},不影响本地订单", order.getOrderNo(), e);
}
}
}
// ==================== 退款异步回调 ====================
@Operation(summary = "支付宝退款异步通知(支付宝服务器回调)",
description = "Content-Type: application/x-www-form-urlencoded。"
+ "支付宝 POST form 方式回调退款结果,验签后更新退款单和订单状态。"
+ "关键入参:app_id、out_trade_no、out_biz_no、refund_fee、sign。"
+ "出参:纯文本 success 或 failure")
@PostMapping("/refund/notify")
public String handleAlipayRefundNotify(HttpServletRequest request) {
Map<String, String> params = toMap(request);
log.info("------收到支付宝退款回调通知------, summary: {}", summarizeNotify(params));
try {
String appId = params.get("app_id");
// ISV 模式下应使用 auth_app_id 定位商家应用
String authAppId = params.get("auth_app_id");
String lookupAppId = (authAppId != null && !authAppId.isEmpty()) ? authAppId : appId;
AlipayConfig config = alipayConfigService.getConfigByAppIdAndType(lookupAppId, "PAY");
if (config == null) {
log.error("支付宝支付配置不存在,appId: {}, authAppId: {}", appId, authAppId);
return "failure";
}
TenantContextHolder.setTenant(config.getTenantId());
if (!alipayNotifyVerifier.verify(params, config)) {
log.warn("支付宝退款回调验签失败");
return "failure";
}
handleAlipayRefundResult(params, config);
return "success";
} catch (Exception e) {
log.error("处理支付宝退款回调失败,将由支付宝重试", e);
return "failure";
} finally {
TenantContextHolder.clear();
}
}
private void handleAlipayRefundResult(Map<String, String> params, AlipayConfig config) {
String outRefundNo = params.get("out_biz_no");
String outTradeNo = params.get("out_trade_no");
log.info("处理支付宝退款结果, 退款单号:{}, 商户订单号:{}", outRefundNo, outTradeNo);
com.central.order.model.Refund refund = refundService.getRefundByNo(outRefundNo);
if (refund == null) {
log.error("退款订单不存在: {}", outRefundNo);
throw new IllegalStateException("退款订单不存在: " + outRefundNo);
}
// 租户一致性校验已移除(与支付回调同理:配置可能由 webApp 降级提供)
if (refund.getState().equals(RefundState.PART.getId())) {
refund.setStatus(OrderStatus.PART_REFUNDED.getId());
} else {
refund.setStatus(OrderStatus.REFUNDED.getId());
}
refund.setRefundTime(new Date());
refundService.updateById(refund);
Order order = orderService.getOrderByNumberWithFallback(refund.getOrderNo(), config.getTenantId());
if (order != null) {
if (refund.getState().equals(RefundState.PART.getId())) {
order.setOrderStatus(OrderStatus.PART_REFUNDED.getId());
} else {
order.setOrderStatus(OrderStatus.REFUNDED.getId());
}
orderService.updateOrder(order);
}
}
// ==================== 工具方法 ====================
private Map<String, String> toMap(HttpServletRequest request) {
// 支付宝 form 回调按 biz 参数 charset 编码(默认 UTF-8)。
// 必须在容器解析参数前 setCharacterEncoding;这里在读取任何参数前先尝试设置 UTF-8,
// 避免先 getParameter 触发解析后再 setCharacterEncoding 不生效的问题。
try {
request.setCharacterEncoding("UTF-8");
} catch (java.io.UnsupportedEncodingException ignored) {
}
Map<String, String> params = new HashMap<>();
Map<String, String[]> requestParams = request.getParameterMap();
for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
String name = entry.getKey();
String[] values = entry.getValue();
String valueStr = (values != null && values.length > 0) ? values[0] : "";
params.put(name, valueStr);
}
return params;
}
/**
* 仅保留排查必需的非敏感字段,避免回调日志泄露 buyer/sign 等信息
*/
private Map<String, String> summarizeNotify(Map<String, String> params) {
Set<String> safeKeys = Set.of(
"out_trade_no", "trade_no", "trade_status",
"app_id", "auth_app_id", "out_biz_no",
"refund_status", "gmt_payment", "gmt_refund");
Map<String, String> safe = new LinkedHashMap<>();
for (String k : safeKeys) {
String v = params.get(k);
if (v != null) {
safe.put(k, v);
}
}
return safe;
}
}
@@ -1,210 +0,0 @@
package com.central.order.controller;
import com.central.alipay.config.AlipayClientFactory;
import com.central.alipay.entity.AlipayConfig;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.order.service.IAlipayConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;
/**
* 支付宝配置管理控制器
*
* @author duzhichao
* @date 2026-05-12
*/
@Slf4j
@RestController
@RequiredArgsConstructor
@Tag(name = "支付宝配置管理", description = "alipay_config 表 CRUD,供管理后台和 Feign 内部调用")
@RequestMapping("/alipay/config")
public class AlipayConfigController {
@Resource
private IAlipayConfigService alipayConfigService;
@Resource
private AlipayClientFactory alipayClientFactory;
// ==================== 管理后台 CRUD 端点 ====================
@Operation(summary = "分页查询支付宝配置",
description = "支持按 type/tenantId/appId/status 筛选,出参 PageResult<AlipayConfig>,敏感字段已脱敏")
@Parameter(name = "page", description = "页码", in = ParameterIn.QUERY, example = "1")
@Parameter(name = "limit", description = "每页条数", in = ParameterIn.QUERY, example = "10")
@Parameter(name = "searchKey", description = "检索字段:type/appId/tenantId", in = ParameterIn.QUERY)
@Parameter(name = "searchValue", description = "检索关键字", in = ParameterIn.QUERY)
@GetMapping("/list")
public Result<PageResult<AlipayConfig>> list(@RequestParam Map<String, Object> params) {
PageResult<AlipayConfig> pageResult = alipayConfigService.findList(params);
if (pageResult != null && pageResult.getData() != null) {
pageResult.getData().forEach(this::maskSensitive);
}
return Result.succeed(pageResult);
}
@Operation(summary = "根据ID查询支付宝配置",
description = "返回单条 AlipayConfig,敏感字段(私钥/公钥/authToken/encryptKey)已脱敏")
@Parameter(name = "id", description = "配置主键ID", required = true, in = ParameterIn.PATH, example = "1")
@GetMapping("/{id}")
public Result<AlipayConfig> getById(@PathVariable Long id) {
AlipayConfig config = alipayConfigService.getById(id);
maskSensitive(config);
return Result.succeed(config);
}
@Operation(summary = "新增支付宝配置",
description = "Body 为 AlipayConfig JSON,必填:tenantId/type/appId")
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "支付宝配置对象", required = true,
content = @Content(schema = @Schema(implementation = AlipayConfig.class)))
@PostMapping
public Result<Boolean> save(@RequestBody AlipayConfig config) {
boolean result = alipayConfigService.saveConfig(config);
if (result) {
// 新增配置可能复用现有 appId(同 appId 不同 subMerchantId / 不同 type),保险起见清空全部缓存
alipayClientFactory.clearAllCache();
}
return Result.succeed(result);
}
@Operation(summary = "更新支付宝配置",
description = "Body 为 AlipayConfig JSON(含 id),增量更新;敏感字段(appPrivateKey/alipayPublicKey/authToken/encryptKey)传入掩码 ****** 表示保留原值")
@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "支付宝配置对象(含 id)", required = true)
@PutMapping
public Result<Boolean> update(@RequestBody AlipayConfig config) {
// 当字段值为掩码时,保留库中原值,避免管理后台误覆盖为 ******
if (config.getId() != null) {
AlipayConfig original = alipayConfigService.getById(config.getId());
if (original != null) {
if (isMasked(config.getAppPrivateKey())) {
config.setAppPrivateKey(original.getAppPrivateKey());
}
if (isMasked(config.getAlipayPublicKey())) {
config.setAlipayPublicKey(original.getAlipayPublicKey());
}
if (isMasked(config.getAuthToken())) {
config.setAuthToken(original.getAuthToken());
}
if (isMasked(config.getEncryptKey())) {
config.setEncryptKey(original.getEncryptKey());
}
}
}
boolean result = alipayConfigService.updateConfig(config);
if (result) {
// 更新后清理缓存:可能改了密钥/证书/subMerchantId/启停,必须使旧 AlipayClient 失效
alipayClientFactory.clearCache(config);
}
return Result.succeed(result);
}
@Operation(summary = "删除支付宝配置")
@Parameter(name = "id", description = "配置主键ID", required = true, in = ParameterIn.PATH, example = "1")
@DeleteMapping("/{id}")
public Result<Boolean> delete(@PathVariable Long id) {
AlipayConfig original = alipayConfigService.getById(id);
boolean result = alipayConfigService.deleteConfig(id);
if (result && original != null) {
alipayClientFactory.clearCache(original);
}
return Result.succeed(result);
}
@Operation(summary = "切换配置启用/禁用状态",
description = "Body: {\"status\": 0|1}")
@Parameter(name = "id", description = "配置主键ID", required = true, in = ParameterIn.PATH, example = "1")
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "{\"status\": 1} 启用, {\"status\": 0} 禁用", required = true)
@PatchMapping("/{id}/status")
public Result<Boolean> toggleStatus(@PathVariable Long id, @RequestBody Map<String, Object> body) {
AlipayConfig config = alipayConfigService.getById(id);
if (config == null) {
return Result.failed("配置不存在");
}
config.setStatus(Integer.valueOf(body.get("status").toString()));
boolean result = alipayConfigService.updateConfig(config);
if (result) {
// 启停切换后必须清理缓存,避免禁用配置仍被复用
alipayClientFactory.clearCache(config);
}
return Result.succeed(result);
}
// ==================== Feign 调用端点(返回原始实体,无 Result 包装) ====================
@Operation(summary = "根据类型+租户ID查询配置(Feign内部调用)",
description = "供 AlipayClientFactory 调用,出参为原始 AlipayConfig 或 null")
@Parameter(name = "type", description = "MINI(小程序登录)/ PAY(交易支付)", required = true, in = ParameterIn.PATH)
@Parameter(name = "tenantId", description = "租户ID", required = true, in = ParameterIn.QUERY, example = "tenant-001")
@GetMapping("/type/{type}")
public AlipayConfig getConfig(@PathVariable String type, @RequestParam String tenantId) {
return alipayConfigService.getConfigByTypeAndTenantId(type, tenantId);
}
@Operation(summary = "根据AppId+类型查询配置(Feign内部调用)",
description = "供 AlipayAuthenticationProvider 调用")
@Parameter(name = "appId", description = "支付宝 AppId", required = true, in = ParameterIn.PATH, example = "2021000000000001")
@Parameter(name = "type", description = "MINI / PAY", in = ParameterIn.QUERY)
@GetMapping("/app/{appId}")
public AlipayConfig getConfigByAppId(@PathVariable("appId") String appId,
@RequestParam(required = false) String type) {
if (type != null && !type.isEmpty()) {
return alipayConfigService.getConfigByAppIdAndType(appId, type);
}
return alipayConfigService.getConfigByAppId(appId);
}
@Operation(summary = "根据AppId查询配置不区分类型(Feign内部调用)",
description = "供回调验签使用")
@Parameter(name = "appId", description = "支付宝 AppId", required = true, in = ParameterIn.PATH, example = "2021000000000001")
@GetMapping("/app/{appId}/any")
public AlipayConfig getConfigByAppIdAny(@PathVariable("appId") String appId) {
return alipayConfigService.getConfigByAppId(appId);
}
@Operation(summary = "根据子商户号查询配置(Feign内部调用,ISV模式)")
@Parameter(name = "subMerchantId", description = "间连商户号 smid", required = true, in = ParameterIn.PATH, example = "2088xxxx")
@GetMapping("/sub/{subMerchantId}")
public AlipayConfig getConfigBySubMerchantId(@PathVariable("subMerchantId") String subMerchantId) {
return alipayConfigService.getConfigBySubMerchantId(subMerchantId);
}
// ==================== 内部工具:敏感字段脱敏 ====================
private static final String MASK = "******";
private void maskSensitive(AlipayConfig config) {
if (config == null) {
return;
}
if (config.getAppPrivateKey() != null && !config.getAppPrivateKey().isEmpty()) {
config.setAppPrivateKey(MASK);
}
if (config.getAlipayPublicKey() != null && !config.getAlipayPublicKey().isEmpty()) {
config.setAlipayPublicKey(MASK);
}
if (config.getAuthToken() != null && !config.getAuthToken().isEmpty()) {
config.setAuthToken(MASK);
}
if (config.getEncryptKey() != null && !config.getEncryptKey().isEmpty()) {
config.setEncryptKey(MASK);
}
}
private boolean isMasked(String value) {
return MASK.equals(value);
}
}
@@ -1,38 +0,0 @@
package com.central.order.controller;
import com.central.common.model.Result;
import com.central.order.service.ICtripDistOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@RequestMapping("/ctrip/dist/order")
@Tag(name = "携程分销订单-手动触发")
public class CtripDistOrderController {
@Autowired
private ICtripDistOrderService ctripDistOrderService;
@Operation(summary = "手动触发创建携程分销订单")
@PostMapping("/manualCreate")
public Result<String> manualCreateCtripDistOrder(
@Parameter(description = "本地订单号") @RequestParam String orderNo,
@Parameter(description = "订单金额(分)") @RequestParam String orderAmount,
@Parameter(description = "携程产品ID") @RequestParam Long ctripProductId,
@Parameter(description = "租户ID") @RequestParam String tenantId,
@Parameter(description = "用户手机号") @RequestParam(required = false) String mobile) {
log.info("手动触发创建携程分销订单,orderNo: {}, ctripProductId: {}", orderNo, ctripProductId);
try {
ctripDistOrderService.createCtripDistOrder(orderNo, orderAmount, ctripProductId, tenantId, mobile);
return Result.succeed("携程分销订单创建请求已提交(异步处理中)");
} catch (Exception e) {
log.error("手动触发创建携程分销订单异常,orderNo: {}", orderNo, e);
return Result.failed("创建失败: " + e.getMessage());
}
}
}
@@ -595,10 +595,15 @@ public class OrderController {
@Operation(summary = "后台管理更新订单") @Operation(summary = "后台管理更新订单")
@PostMapping("/update/order") @PostMapping("/update/order")
public Result updateOrder(@RequestBody Order order) { public Result updateOrder(@RequestBody Order order) {
LoginAppUser loginAppUser = LoginUserContextHolder.getUser();
//
if (loginAppUser.getId() == 1 || loginAppUser.getId() == 1073) {
boolean res = orderService.updateOrder(order); boolean res = orderService.updateOrder(order);
if (res){ if (res){
return Result.succeed("已更新"); return Result.succeed("已更新");
} }
}
return Result.failed("请重试"); return Result.failed("请重试");
} }
@@ -6,7 +6,6 @@ import com.central.common.feign.UserService;
import com.central.common.model.*; import com.central.common.model.*;
import com.central.order.constants.EditTaskStatus; import com.central.order.constants.EditTaskStatus;
import com.central.order.enums.OrderStatus; import com.central.order.enums.OrderStatus;
import com.central.order.enums.PayTypeEnum;
import com.central.order.feign.FileCenterService; import com.central.order.feign.FileCenterService;
import com.central.order.model.*; import com.central.order.model.*;
import com.central.order.model.params.FileDownloadRequest; import com.central.order.model.params.FileDownloadRequest;
@@ -94,9 +93,6 @@ public class OrderFileController {
@Autowired @Autowired
private WxMiniSubscribeService wxMiniSubscribeService; private WxMiniSubscribeService wxMiniSubscribeService;
@Autowired
private AlipayMiniSubscribeService alipayMiniSubscribeService;
@Autowired @Autowired
private IEditTaskService editTaskService; private IEditTaskService editTaskService;
@@ -318,8 +314,6 @@ public class OrderFileController {
if (updateResult) { if (updateResult) {
log.info("订单状态已更新为UPLOADED: orderNo={}, oldStatus={}, newStatus={}", log.info("订单状态已更新为UPLOADED: orderNo={}, oldStatus={}, newStatus={}",
latestOrder.getOrderNo(), oldStatus, OrderStatus.UPLOADED.getId()); latestOrder.getOrderNo(), oldStatus, OrderStatus.UPLOADED.getId());
// 首次达标才预热订单文件到CDN,避免重复预热
prefetchOrderFilesToCdn(latestOrder.getOrderNo());
} else { } else {
log.error("订单状态更新为UPLOADED失败: orderNo={}", latestOrder.getOrderNo()); log.error("订单状态更新为UPLOADED失败: orderNo={}", latestOrder.getOrderNo());
} }
@@ -328,6 +322,9 @@ public class OrderFileController {
//发送用户素材上传成功通知 //发送用户素材上传成功通知
sendMessageForResouresUploaded(latestOrder,tourism); sendMessageForResouresUploaded(latestOrder,tourism);
// 预热订单相关的文件到CDN
prefetchOrderFilesToCdn(latestOrder.getOrderNo());
// 7分钟后如果状态仍为UPLOADED,则自动更新为COMPLETE;若已完成则不再安排 // 7分钟后如果状态仍为UPLOADED,则自动更新为COMPLETE;若已完成则不再安排
if (!isComplete) { if (!isComplete) {
scheduleAutoCompleteIfStillUploaded(latestOrder.getOrderNo()); scheduleAutoCompleteIfStillUploaded(latestOrder.getOrderNo());
@@ -421,6 +418,12 @@ public class OrderFileController {
* @param tourism * @param tourism
*/ */
private void sendMessageForResouresUploaded(Order order, Tourism tourism) { private void sendMessageForResouresUploaded(Order order, Tourism tourism) {
// 发送小程序订阅消息,用户素材上传完成
SysUser sysUser = userCenterService.findUserById(order.getUserId());
if (sysUser.getOpenId() != null) {
String tip = "素材上传完成";
String orderName = tourism.getTourismName(); String orderName = tourism.getTourismName();
String pageUrl = "pages/album/album"; String pageUrl = "pages/album/album";
// 处理支付时间为空的情况 // 处理支付时间为空的情况
@@ -428,31 +431,16 @@ public class OrderFileController {
if (order.getPayTime() != null) { if (order.getPayTime() != null) {
payTimeStr = DateUtils.sdf.format(order.getPayTime()); payTimeStr = DateUtils.sdf.format(order.getPayTime());
} }
// 根据 payType 发送小程序通知(微信 or 支付宝)
Integer payType = order.getPayType();
if (PayTypeEnum.WECHAT_PAY.getCode().equals(payType)) {
SysUser sysUser = userCenterService.findUserById(order.getUserId());
if (sysUser.getOpenId() != null) {
wxMiniSubscribeService.sendServiceProcessMsg( wxMiniSubscribeService.sendServiceProcessMsg(
sysUser.getOpenId(), sysUser.getOpenId(),
orderName, orderName,
"素材上传完成", tip,
order.getOrderNo(), order.getOrderNo(),
payTimeStr, payTimeStr,
"", "",
pageUrl pageUrl
); );
} }
} else if (PayTypeEnum.ALIPAY_PAY.getCode().equals(payType)) {
if (order.getTenantId() != null && !order.getTenantId().isEmpty()) {
alipayMiniSubscribeService.sendServiceProcessMsg(
order.getUserId(), order.getTenantId(),
orderName, "素材上传完成",
order.getOrderNo(), payTimeStr, pageUrl
);
}
}
} }
/** /**
@@ -476,14 +464,9 @@ public class OrderFileController {
return; return;
} }
// 收集所有文件的URL(跳过视频文件,视频不做预热,避免CDN回源流量暴增) // 收集所有文件的URL
List<String> fileUrls = new ArrayList<>(); List<String> fileUrls = new ArrayList<>();
for (OrderFile orderFile : orderFiles) { for (OrderFile orderFile : orderFiles) {
// 跳过视频文件:视频体积大且点播命中率低,预热会造成大量CDN回源流量
if (isVideoFile(orderFile.getFileType())) {
log.debug("跳过视频文件预热,文件路径: {}, 类型: {}", orderFile.getFilePath(), orderFile.getFileType());
continue;
}
try { try {
String viewUrl = fileCenterService.getViewUrlByPath(orderFile.getFilePath()); String viewUrl = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
if (viewUrl != null && !viewUrl.trim().isEmpty()) { if (viewUrl != null && !viewUrl.trim().isEmpty()) {
@@ -536,15 +519,6 @@ public class OrderFileController {
return url; return url;
} }
/**
* 判断是否为视频文件
* @param fileType 文件类型(如 video/mp4、image/jpeg)
* @return 是否为视频
*/
private boolean isVideoFile(String fileType) {
return fileType != null && fileType.startsWith("video/");
}
@Operation(summary = "删除文件") @Operation(summary = "删除文件")
@DeleteMapping( "/{id}") @DeleteMapping( "/{id}")
@@ -1,6 +1,5 @@
package com.central.order.controller; package com.central.order.controller;
import com.central.alipay.service.AlipayQrcodeService;
import com.central.common.model.PageResult; import com.central.common.model.PageResult;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.common.utils.StringUtils; import com.central.common.utils.StringUtils;
@@ -22,7 +21,6 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
@@ -61,15 +59,6 @@ public class QrCodeController {
@Autowired @Autowired
private IPackagePlanService packagePlanService; private IPackagePlanService packagePlanService;
@Autowired
private AlipayQrcodeService alipayQrcodeService;
@Value("${zlt.security.alipay.pagePath:pages/link/link}")
private String alipayPagePath;
@Value("${zlt.security.alipay.queryKey:uuid}")
private String alipayQueryKey;
/** /**
* 列表 * 列表
*/ */
@@ -84,9 +73,6 @@ public class QrCodeController {
if (pageResult.getResp_code() == 0){ if (pageResult.getResp_code() == 0){
for (QrCode qrCode: pageResult.getData()){ for (QrCode qrCode: pageResult.getData()){
qrCode.setViewUrl(fileCenterService.getViewUrlByPath(qrCode.getFilePath())); qrCode.setViewUrl(fileCenterService.getViewUrlByPath(qrCode.getFilePath()));
if (qrCode.getAlipayFilePath() != null && !qrCode.getAlipayFilePath().isEmpty()) {
qrCode.setAlipayViewUrl(fileCenterService.getS3ViewUrlByPath(qrCode.getAlipayFilePath()));
}
} }
} }
return pageResult; return pageResult;
@@ -266,42 +252,4 @@ public class QrCodeController {
return result; return result;
} }
@Operation(summary = "为已存在的二维码生成支付宝小程序码(同行追加,不另起一行)")
@PostMapping("/{id}/alipay")
@Transactional(rollbackFor = Exception.class)
public Result<QrCode> generateAlipayQrcode(@PathVariable("id") Long id) throws Exception {
QrCode qrCode = qrCodeService.getById(id);
Assert.notNull(qrCode, "二维码不存在");
Assert.hasText(qrCode.getCodeId(), "codeId 缺失");
Assert.hasText(qrCode.getTenantId(), "tenantId 缺失");
String qrCodeUrl = alipayQrcodeService.createMiniQrcode(
qrCode.getTenantId(),
qrCode.getCodeId(),
alipayPagePath,
alipayQueryKey,
qrCode.getName());
if (qrCodeUrl == null || qrCodeUrl.isEmpty()) {
return Result.failed("支付宝二维码生成失败:qr_code_url 为空");
}
Result<Map> upload = fileCenterService.uploadQrCodeToS3ByUrl(qrCode.getCodeId(), qrCodeUrl, "png");
if (upload == null || upload.getResp_code() != 0) {
return Result.failed("支付宝二维码上传 S3 失败");
}
Object fileId = upload.getData().get("fileId");
Object filePath = upload.getData().get("filePath");
if (fileId == null || filePath == null) {
return Result.failed("支付宝二维码上传响应缺少 fileId/filePath");
}
qrCode.setAlipayFileId(fileId.toString());
qrCode.setAlipayFilePath(filePath.toString());
qrCodeService.updateById(qrCode);
// 列表展示用:同步把 view url 拉一次
qrCode.setViewUrl(fileCenterService.getViewUrlByPath(qrCode.getFilePath()));
qrCode.setAlipayViewUrl(fileCenterService.getS3ViewUrlByPath(qrCode.getAlipayFilePath()));
return Result.succeed(qrCode, "支付宝二维码生成成功");
}
} }
@@ -5,10 +5,7 @@ import com.central.common.feign.UserService;
import com.central.common.model.PageResult; import com.central.common.model.PageResult;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.common.model.SysUser; import com.central.common.model.SysUser;
import com.central.alipay.entity.AlipayConfig;
import com.central.alipay.service.AlipayRefundService;
import com.central.order.enums.OrderStatus; import com.central.order.enums.OrderStatus;
import com.central.order.enums.PayTypeEnum;
import com.central.order.enums.RefundState; import com.central.order.enums.RefundState;
import com.central.order.model.Order; import com.central.order.model.Order;
import com.central.order.model.QrCode; import com.central.order.model.QrCode;
@@ -67,15 +64,6 @@ public class RefundController {
@Autowired @Autowired
private IQrCodeService qrCodeService; private IQrCodeService qrCodeService;
@Autowired
private com.central.order.service.ICtripDistOrderService ctripDistOrderService;
@Autowired
private com.central.order.service.IAlipayConfigService alipayConfigService;
@Autowired
private AlipayRefundService alipayRefundService;
@Value("${tencent.refund-notify-url}") @Value("${tencent.refund-notify-url}")
private String refundNotifyUrl; private String refundNotifyUrl;
@@ -165,12 +153,6 @@ public class RefundController {
// 检查订单是否存在 // 检查订单是否存在
Order order = orderService.getOrderByNumber(refund.getOrderNo()); Order order = orderService.getOrderByNumber(refund.getOrderNo());
Assert.notNull(order, "ORDER DATA不存在"); Assert.notNull(order, "ORDER DATA不存在");
// 校验退款单存在并与订单一致
com.central.order.model.Refund refundDb = refundService.getRefundByNo(refund.getRefundNo());
Assert.notNull(refundDb, "退款订单不存在");
if (!order.getOrderNo().equals(refundDb.getOrderNo())) {
return Result.failed("退款单与订单不匹配");
}
if (!order.getOrderStatus().equals(OrderStatus.REFUNDING.getId())){ if (!order.getOrderStatus().equals(OrderStatus.REFUNDING.getId())){
return Result.failed("请重试"); return Result.failed("请重试");
} }
@@ -178,23 +160,14 @@ public class RefundController {
return Result.failed("该状态不支持审核"); return Result.failed("该状态不支持审核");
} }
if (refund.getState().equals(RefundState.APPROVED.getId())){ if (refund.getState().equals(RefundState.APPROVED.getId())){
// 同步退款(支付宝/微信)成功后,立即推进本地退款单与订单为已退款,避免长期停留在退款中 dealRefundRequest(order);
routeRefundByPayType(order, null);
refundDb.setState(RefundState.APPROVED.getId());
refundDb.setStatus(OrderStatus.REFUNDED.getId());
refundDb.setRefundTime(new java.util.Date());
refundService.updateById(refundDb);
order.setOrderStatus(OrderStatus.REFUNDED.getId());
orderService.updateOrder(order);
return Result.succeed("已处理退款"); return Result.succeed("已处理退款");
} }
if (refund.getState().equals(RefundState.REFUSED.getId())){ if (refund.getState().equals(RefundState.REFUSED.getId())){
order.setOrderStatus(OrderStatus.REFUND_FAILED.getId()); order.setOrderStatus(OrderStatus.REFUND_FAILED.getId());
refundDb.setStatus(OrderStatus.REFUND_FAILED.getId()); refund.setStatus(OrderStatus.REFUND_FAILED.getId());
refundDb.setState(RefundState.REFUSED.getId());
refundDb.setApproveReason(refund.getApproveReason());
orderService.updateOrder(order); orderService.updateOrder(order);
refundService.updateById(refundDb); refundService.updateById(refund);
return Result.succeed("处理成功"); return Result.succeed("处理成功");
} }
return Result.failed("处理退款失败"); return Result.failed("处理退款失败");
@@ -210,19 +183,7 @@ public class RefundController {
Order order = orderService.getOrderByNumber(refundRequest.getOrderNo()); Order order = orderService.getOrderByNumber(refundRequest.getOrderNo());
Assert.notNull(order, "ORDER DATA不存在"); Assert.notNull(order, "ORDER DATA不存在");
com.central.order.model.Refund refundorder = refundService.getRefundByNo(refundRequest.getRefundNo()); com.central.order.model.Refund refundorder = refundService.getRefundByNo(refundRequest.getRefundNo());
Assert.notNull(refundorder, "退款订单不存在"); Assert.notNull(order, "退款订单不存在");
// 退款单必须与订单匹配(订单号、租户、用户)
if (!order.getOrderNo().equals(refundorder.getOrderNo())) {
return Result.failed("退款单与订单不匹配");
}
if (order.getTenantId() != null && refundorder.getTenantId() != null
&& !order.getTenantId().equals(refundorder.getTenantId())) {
return Result.failed("退款单与订单租户不一致");
}
if (order.getUserId() != null && refundorder.getUserId() != null
&& !order.getUserId().equals(refundorder.getUserId())) {
return Result.failed("退款单与订单用户不一致");
}
if (!order.getOrderStatus().equals(OrderStatus.REFUNDING.getId())){ if (!order.getOrderStatus().equals(OrderStatus.REFUNDING.getId())){
return Result.failed("订单状态不支持退款"); return Result.failed("订单状态不支持退款");
} }
@@ -231,35 +192,20 @@ public class RefundController {
} }
if (refundRequest.getState().equals(RefundState.APPROVED.getId())){ if (refundRequest.getState().equals(RefundState.APPROVED.getId())){
routeRefundByPayType(order, null); dealCustomRefundAmountRequest(order,null);
refundorder.setApproveReason(refundRequest.getApproveReason()); refundorder.setApproveReason(refundRequest.getApproveReason());
refundorder.setState(refundRequest.getState()); //全额退款 refundorder.setState(refundRequest.getState()); //全额退款
// 同步全额退款成功后,推进本地状态到已退款
refundorder.setStatus(OrderStatus.REFUNDED.getId());
refundorder.setRefundTime(new java.util.Date());
refundService.updateById(refundorder); refundService.updateById(refundorder);
order.setOrderStatus(OrderStatus.REFUNDED.getId());
orderService.updateOrder(order);
// 全额退款成功后,根据二维码配置判断是否需要异步退订携程分销订单
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
if (qrCode != null && qrCode.getEnableCtripOrder() != null && qrCode.getEnableCtripOrder() == 1) {
ctripDistOrderService.cancelCtripDistOrder(order.getOrderNo(), "用户申请全额退款");
}
return Result.succeed("已处理全额退款"); return Result.succeed("已处理全额退款");
} }
if (refundRequest.getState().equals(RefundState.PART.getId())){ if (refundRequest.getState().equals(RefundState.PART.getId())){
routeRefundByPayType(order, refundRequest.getRefundAmount()); dealCustomRefundAmountRequest(order,refundRequest.getRefundAmount());
refundorder.setApproveReason(refundRequest.getApproveReason()); refundorder.setApproveReason(refundRequest.getApproveReason());
refundorder.setState(refundRequest.getState()); //部分退款 refundorder.setState(refundRequest.getState()); //部分退款
if(refundRequest.getRefundAmount()!=null){ if(refundRequest.getRefundAmount()!=null){
refundorder.setRefundAmount(refundRequest.getRefundAmount()); refundorder.setRefundAmount(refundRequest.getRefundAmount());
} }
// 同步部分退款成功后,推进本地状态到部分已退款
refundorder.setStatus(OrderStatus.PART_REFUNDED.getId());
refundorder.setRefundTime(new java.util.Date());
refundService.updateById(refundorder); refundService.updateById(refundorder);
order.setOrderStatus(OrderStatus.PART_REFUNDED.getId());
orderService.updateOrder(order);
return Result.succeed("已处理部分退款"); return Result.succeed("已处理部分退款");
} }
if (refundRequest.getState().equals(RefundState.REFUSED.getId())){ if (refundRequest.getState().equals(RefundState.REFUSED.getId())){
@@ -356,88 +302,6 @@ public class RefundController {
} }
} }
/**
* 按 payType 路由退款到对应渠道
*
* @param order 订单
* @param customAmount 自定义退款金额(null 表示全额退款)
*/
private void routeRefundByPayType(Order order, String customAmount) {
PayTypeEnum channel = PayTypeEnum.getByCode(order.getPayType());
// 历史订单 payType 为 null 的兜底:走微信退款
if (channel == null) {
log.warn("订单 payType 为空,兜底走微信退款,orderNo: {}", order.getOrderNo());
if (customAmount != null) {
dealCustomRefundAmountRequest(order, customAmount);
} else {
dealRefundRequest(order);
}
return;
}
switch (channel) {
case WECHAT_PAY:
if (customAmount != null) {
dealCustomRefundAmountRequest(order, customAmount);
} else {
dealRefundRequest(order);
}
break;
case ALIPAY_PAY:
alipayRefund(order, customAmount);
break;
case COUPON_PAY:
log.info("优惠券支付退款,orderNo: {}", order.getOrderNo());
// 优惠券退款逻辑由现有流程处理
break;
case FEIPAI_VERIFY:
throw new RuntimeException("第三方核销订单不支持系统退款");
default:
throw new RuntimeException("未知支付类型: " + order.getPayType());
}
}
/**
* 支付宝退款
*/
private void alipayRefund(Order order, String customAmount) {
try {
TenantContextHolder.setTenant(order.getTenantId());
// 获取支付宝配置
AlipayConfig config = alipayConfigService.getConfigByTypeAndTenantId("PAY", order.getTenantId());
if (config == null) {
log.error("支付宝支付配置不存在,租户ID: {}", order.getTenantId());
throw new RuntimeException("支付宝支付配置不存在");
}
AlipayRefundService.AlipayRefundRequest req = new AlipayRefundService.AlipayRefundRequest();
req.setOutTradeNo(order.getOrderNo());
req.setOutRequestNo("RF" + order.getOrderNo());
req.setRefundReason("用户申请退款");
// 退款金额:DB 与 customAmount 均以"分"存储,支付宝 SDK refund_amount 需要"元"
String refundAmountFen = customAmount != null ? customAmount : order.getOrderAmount();
String refundAmount = StringUtils.fenToYuanAmount(refundAmountFen);
req.setRefundAmount(refundAmount);
com.alipay.api.response.AlipayTradeRefundResponse response = alipayRefundService.refund(config, req);
if (!response.isSuccess()) {
log.error("支付宝退款失败, subCode: {}, subMsg: {}", response.getSubCode(), response.getSubMsg());
throw new RuntimeException("支付宝退款失败: " + response.getSubMsg());
}
log.info("支付宝退款成功,订单号: {}, 退款金额: {}, fundChange: {}",
order.getOrderNo(), refundAmount, response.getFundChange());
} catch (Exception e) {
log.error("支付宝退款请求失败,订单号: {}, 异常: {}", order.getOrderNo(), e.getMessage(), e);
throw new RuntimeException("支付宝退款失败: " + e.getMessage(), e);
} finally {
TenantContextHolder.clear();
}
}
/** /**
* 微信退款申请 * 微信退款申请
* @param order * @param order
@@ -4,7 +4,6 @@ import com.central.common.context.TenantContextHolder;
import com.central.common.feign.UserService; import com.central.common.feign.UserService;
import com.central.common.model.SysUser; import com.central.common.model.SysUser;
import com.central.order.enums.OrderStatus; import com.central.order.enums.OrderStatus;
import com.central.order.enums.PayTypeEnum;
import com.central.order.enums.RefundState; import com.central.order.enums.RefundState;
import com.central.order.model.Order; import com.central.order.model.Order;
import com.central.order.model.QrCode; import com.central.order.model.QrCode;
@@ -159,7 +158,6 @@ public class WxPayController {
// 2. 更新订单状态 // 2. 更新订单状态
order.setOrderStatus(OrderStatus.PAID.getId()); order.setOrderStatus(OrderStatus.PAID.getId());
order.setPayType(PayTypeEnum.WECHAT_PAY.getCode());
order.setPayTime(new Date()); order.setPayTime(new Date());
orderService.updateOrder(order); orderService.updateOrder(order);
@@ -222,7 +220,6 @@ public class WxPayController {
// 2. 更新订单状态 // 2. 更新订单状态
order.setOrderStatus(OrderStatus.PAID.getId()); order.setOrderStatus(OrderStatus.PAID.getId());
order.setPayType(PayTypeEnum.WECHAT_PAY.getCode());
order.setPayTime(new Date()); order.setPayTime(new Date());
orderService.updateOrder(order); orderService.updateOrder(order);
@@ -19,17 +19,7 @@ public enum PayTypeEnum {
/** /**
* 优惠券支付 * 优惠券支付
*/ */
COUPON_PAY(2, "优惠券支付"), COUPON_PAY(2, "优惠券支付");
/**
* 第三方聚到核销(补齐遗留常量)
*/
FEIPAI_VERIFY(3, "第三方聚到核销"),
/**
* 支付宝支付(本期新增)
*/
ALIPAY_PAY(4, "支付宝支付");
private final Integer code; private final Integer code;
private final String desc; private final String desc;
@@ -4,10 +4,8 @@ import com.central.common.constant.ServiceNameConstants;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.order.feign.fallback.CouponCenterServiceFallbackFactory; import com.central.order.feign.fallback.CouponCenterServiceFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map; import java.util.Map;
@@ -19,10 +17,4 @@ public interface CouponCenterService {
*/ */
@PostMapping("/ctrip/dist/order/create") @PostMapping("/ctrip/dist/order/create")
Result<String> createCtripDistOrder(@RequestBody Map<String, Object> params); Result<String> createCtripDistOrder(@RequestBody Map<String, Object> params);
/**
* 退订携程分销订单
*/
@PostMapping("/ctrip/dist/order/cancel/{orderNo}")
Result<String> cancelCtripDistOrder(@PathVariable("orderNo") String orderNo, @RequestParam("reason") String reason);
} }
@@ -8,8 +8,6 @@ import com.central.order.model.dto.AgeDeviceLocationDTO;
import com.central.order.model.dto.BoatRealtimePositionDTO; import com.central.order.model.dto.BoatRealtimePositionDTO;
import com.central.order.model.dto.DroneLatestTrackPointDTO; import com.central.order.model.dto.DroneLatestTrackPointDTO;
import com.central.order.mission.VO.TakeoffRequestVO; import com.central.order.mission.VO.TakeoffRequestVO;
import com.central.order.mission.VO.FlyToPointRequestVO;
import com.central.order.mission.VO.FlyToPointUpdateRequestVO;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@@ -41,10 +39,6 @@ public interface DeviceCenterService {
@PostMapping("/device/command/takeoff") @PostMapping("/device/command/takeoff")
Result<String> takeoff(@RequestBody TakeoffRequestVO request); Result<String> takeoff(@RequestBody TakeoffRequestVO request);
@Operation(summary = "无人机返航")
@PostMapping("/device/command/return")
Result<String> returnHome(@RequestParam("deviceSn") String deviceSn);
/** /**
* 执行航线任务 * 执行航线任务
* *
@@ -139,25 +133,4 @@ public interface DeviceCenterService {
@Operation(summary = "获取无人机最新轨迹点") @Operation(summary = "获取无人机最新轨迹点")
@GetMapping("/api/device/drone/track/latest/{deviceSn}") @GetMapping("/api/device/drone/track/latest/{deviceSn}")
Result<DroneLatestTrackPointDTO> getDroneLatestTrackPoint(@PathVariable("deviceSn") String deviceSn); Result<DroneLatestTrackPointDTO> getDroneLatestTrackPoint(@PathVariable("deviceSn") String deviceSn);
/**
* 指点飞行 - 首次飞向目标点
*/
@Operation(summary = "无人机指点飞行 - 飞向目标")
@PostMapping("/device/command/flyToPoint")
Result<String> flyToPoint(@RequestBody FlyToPointRequestVO request);
/**
* 指点飞行 - 更新目标点(连续指点)
*/
@Operation(summary = "无人机指点飞行 - 更新目标点")
@PostMapping("/device/command/flyToPointUpdate")
Result<String> flyToPointUpdate(@RequestBody FlyToPointUpdateRequestVO request);
/**
* 指点飞行 - 停止指点飞行
*/
@Operation(summary = "无人机指点飞行 - 停止")
@PostMapping("/device/command/flyToPointStop")
Result<String> flyToPointStop(@RequestParam("deviceSn") String deviceSn);
} }
@@ -36,20 +36,6 @@ public interface FileCenterService {
@GetMapping("/qrcode/{codeId}") @GetMapping("/qrcode/{codeId}")
Result<Map> uploadQrCodeFile(@PathVariable("codeId") String codeId) throws Exception; Result<Map> uploadQrCodeFile(@PathVariable("codeId") String codeId) throws Exception;
/**
* 拉取外部图片 URL 字节并强制入 S3(用于支付宝小程序二维码)
*/
@GetMapping("/qrcode/s3/by-url")
Result<Map> uploadQrCodeToS3ByUrl(@RequestParam("codeId") String codeId,
@RequestParam("qrUrl") String qrUrl,
@RequestParam(value = "suffix", required = false, defaultValue = "png") String suffix) throws Exception;
/**
* 强制返回 S3 预签名 URL(绕开智能路由)
*/
@GetMapping("/files/s3/path")
String getS3ViewUrlByPath(@RequestParam("path") String path);
@PostMapping("/path") @PostMapping("/path")
FileInfo creatFileInfo(@RequestBody String path); FileInfo creatFileInfo(@RequestBody String path);
@@ -20,12 +20,6 @@ public class CouponCenterServiceFallbackFactory implements FallbackFactory<Coupo
log.error("调用coupon-center创建携程分销订单失败,params: {}", params, cause); log.error("调用coupon-center创建携程分销订单失败,params: {}", params, cause);
return Result.failed("调用coupon-center失败: " + cause.getMessage()); return Result.failed("调用coupon-center失败: " + cause.getMessage());
} }
@Override
public Result<String> cancelCtripDistOrder(String orderNo, String reason) {
log.error("调用coupon-center退订携程分销订单失败,orderNo: {}, reason: {}", orderNo, reason, cause);
return Result.failed("调用coupon-center退订失败: " + cause.getMessage());
}
}; };
} }
} }
@@ -7,8 +7,6 @@ import com.central.order.model.dto.AgeDeviceLocationDTO;
import com.central.order.model.dto.BoatRealtimePositionDTO; import com.central.order.model.dto.BoatRealtimePositionDTO;
import com.central.order.model.dto.DroneLatestTrackPointDTO; import com.central.order.model.dto.DroneLatestTrackPointDTO;
import com.central.order.mission.VO.TakeoffRequestVO; import com.central.order.mission.VO.TakeoffRequestVO;
import com.central.order.mission.VO.FlyToPointRequestVO;
import com.central.order.mission.VO.FlyToPointUpdateRequestVO;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -45,12 +43,6 @@ public class DeviceCenterServiceFallbackFactory implements FallbackFactory<Devic
return Result.failed("设备中心服务调用失败"); return Result.failed("设备中心服务调用失败");
} }
@Override
public Result<String> returnHome(String deviceSn) {
log.error("调用设备中心returnHome失败: deviceSn={}, error={}", deviceSn, cause.getMessage());
return Result.failed("设备中心服务调用失败");
}
@Override @Override
public Result<String> executeWayline(String deviceSn, String waylineId, String missionCode) { public Result<String> executeWayline(String deviceSn, String waylineId, String missionCode) {
log.error("调用设备中心executeWayline失败: deviceSn={}, waylineId={}, missionCode={}, error={}", log.error("调用设备中心executeWayline失败: deviceSn={}, waylineId={}, missionCode={}, error={}",
@@ -106,24 +98,6 @@ public class DeviceCenterServiceFallbackFactory implements FallbackFactory<Devic
log.error("调用设备中心getDroneLatestTrackPoint失败: deviceSn={}, error={}", deviceSn, cause.getMessage()); log.error("调用设备中心getDroneLatestTrackPoint失败: deviceSn={}, error={}", deviceSn, cause.getMessage());
return Result.failed("设备中心服务调用失败"); return Result.failed("设备中心服务调用失败");
} }
@Override
public Result<String> flyToPoint(FlyToPointRequestVO request) {
log.error("调用设备中心flyToPoint失败: deviceSn={}, error={}", request.getDeviceSn(), cause.getMessage());
return Result.failed("设备中心服务调用失败");
}
@Override
public Result<String> flyToPointUpdate(FlyToPointUpdateRequestVO request) {
log.error("调用设备中心flyToPointUpdate失败: deviceSn={}, error={}", request.getDeviceSn(), cause.getMessage());
return Result.failed("设备中心服务调用失败");
}
@Override
public Result<String> flyToPointStop(String deviceSn) {
log.error("调用设备中心flyToPointStop失败: deviceSn={}, error={}", deviceSn, cause.getMessage());
return Result.failed("设备中心服务调用失败");
}
}; };
} }
} }
@@ -41,17 +41,6 @@ public class FileCenterServiceFallbackFactory implements FallbackFactory<FileCen
return null; return null;
} }
@Override
public Result<Map> uploadQrCodeToS3ByUrl(String codeId, String qrUrl, String suffix) throws Exception {
log.warn("file-center 调用失败,支付宝二维码上传降级返回 null, codeId={}", codeId, cause);
return null;
}
@Override
public String getS3ViewUrlByPath(String path) {
return "";
}
@Override @Override
public FileInfo creatFileInfo(String path) { public FileInfo creatFileInfo(String path) {
return null; return null;
@@ -11,7 +11,6 @@ import com.central.order.model.Message;
import com.central.order.model.Order; import com.central.order.model.Order;
import com.central.order.model.QrCode; import com.central.order.model.QrCode;
import com.central.order.model.Tourism; import com.central.order.model.Tourism;
import com.central.order.enums.PayTypeEnum;
import com.central.order.service.*; import com.central.order.service.*;
import com.central.order.service.impl.FeipaiNotifyServiceImpl; import com.central.order.service.impl.FeipaiNotifyServiceImpl;
import com.central.order.util.DateUtils; import com.central.order.util.DateUtils;
@@ -43,8 +42,6 @@ public class OrderStatusChangeListener {
@Autowired @Autowired
private WxMiniSubscribeService wxMiniSubscribeService; private WxMiniSubscribeService wxMiniSubscribeService;
@Autowired @Autowired
private AlipayMiniSubscribeService alipayMiniSubscribeService;
@Autowired
private FeipaiNotifyServiceImpl feipaiNotifyService; private FeipaiNotifyServiceImpl feipaiNotifyService;
@EventListener @EventListener
@@ -167,15 +164,27 @@ public class OrderStatusChangeListener {
private void handlePaymentSuccess(Order order, Tourism tourism) { private void handlePaymentSuccess(Order order, Tourism tourism) {
try { try {
// 1. 查询订单排队信息 // 1. 发送微信通知
SysUser sysUser = userCenterService.findUserById(order.getUserId());
// 2. 查询订单排队信息
Integer queue = orderService.getOrderRankingByOrderIdAndDevice(order.getId(), order.getDeviceSn()); Integer queue = orderService.getOrderRankingByOrderIdAndDevice(order.getId(), order.getDeviceSn());
// 发送小程序订阅消息
if (sysUser.getOpenId() != null) {
String tip = "支付成功,当前排第"+queue+"位";
String orderName = tourism.getTourismName(); String orderName = tourism.getTourismName();
String pageUrl = "pages/task/task"; String pageUrl = "pages/task/task";
String tip = "支付成功,当前排第" + queue + "位"; wxMiniSubscribeService.sendServiceProcessMsg(
String orderTime = DateUtils.sdf.format(order.getPayTime()); sysUser.getOpenId(),
orderName,
// 根据 payType 发送小程序通知(微信 or 支付宝) tip,
sendSubscribeMsgByPayType(order, orderName, tip, order.getOrderNo(), orderTime, pageUrl); order.getOrderNo(),
DateUtils.sdf.format(order.getPayTime()),
"",
pageUrl
);
}
// 2. 记录支付成功日志 // 2. 记录支付成功日志
log.info("订单支付成功: orderNo={}, amount={}, tourismName={}", log.info("订单支付成功: orderNo={}, amount={}, tourismName={}",
@@ -222,74 +231,108 @@ public class OrderStatusChangeListener {
/** /**
* 退款申请成功(退款中)通知 * 退款申请成功(退款中)通知
* @param order
* @param tourism
*/ */
private void sendMessageForRefunding(Order order, Tourism tourism) { private void sendMessageForRefunding(Order order, Tourism tourism) {
try { // 发送小程序订阅消息,用户素材上传完成
SysUser sysUser = userCenterService.findUserById(order.getUserId());
if (sysUser.getOpenId() != null) {
String tip = "您的订单正在退款中";
String orderName = tourism.getTourismName(); String orderName = tourism.getTourismName();
String pageUrl = "pages/task/task"; String pageUrl = "pages/task/task";
String orderTime = DateUtils.sdf.format(order.getPayTime()); wxMiniSubscribeService.sendServiceProcessMsg(
sysUser.getOpenId(),
sendSubscribeMsgByPayType(order, orderName, "您的订单正在退款中", orderName,
order.getOrderNo(), orderTime, pageUrl); tip,
} catch (Exception e) { order.getOrderNo(),
log.error("退款中通知发送失败,不影响主流程: orderNo={}", order.getOrderNo(), e); DateUtils.sdf.format(order.getPayTime()),
"",
pageUrl
);
} }
} }
/** /**
* 退款完成通知 * 退款完成通知
* @param order
* @param tourism
*/ */
private void sendMessageForRefunded(Order order, Tourism tourism) { private void sendMessageForRefunded(Order order, Tourism tourism) {
try { // 发送小程序订阅消息,用户素材上传完成
SysUser sysUser = userCenterService.findUserById(order.getUserId());
if (sysUser.getOpenId() != null) {
String tip = "您的订单退款已完成";
String orderName = tourism.getTourismName(); String orderName = tourism.getTourismName();
String pageUrl = "pages/task/task"; String pageUrl = "pages/task/task";
String orderTime = DateUtils.sdf.format(order.getPayTime()); wxMiniSubscribeService.sendServiceProcessMsg(
sysUser.getOpenId(),
sendSubscribeMsgByPayType(order, orderName, "您的订单退款已完成", orderName,
order.getOrderNo(), orderTime, pageUrl); tip,
} catch (Exception e) { order.getOrderNo(),
log.error("退款完成通知发送失败,不影响主流程: orderNo={}", order.getOrderNo(), e); DateUtils.sdf.format(order.getPayTime()),
"",
pageUrl
);
} }
} }
/** /**
* 素材上传完成小程序通知 * 素材上传完成小程序通知
* @param order
* @param tourism
*/ */
private void sendMessageForResouresUploaded(Order order, Tourism tourism) { private void sendMessageForResouresUploaded(Order order, Tourism tourism) {
try { // 发送小程序订阅消息,用户素材上传完成
SysUser sysUser = userCenterService.findUserById(order.getUserId());
if (sysUser.getOpenId() != null) {
String tip = "素材上传完成";
String orderName = tourism.getTourismName(); String orderName = tourism.getTourismName();
String pageUrl = "pages/album/album"; String pageUrl = "pages/album/album";
String orderTime = ""; wxMiniSubscribeService.sendServiceProcessMsg(
if (order.getPayTime() != null) { sysUser.getOpenId(),
orderTime = DateUtils.sdf.format(order.getPayTime()); orderName,
} tip,
order.getOrderNo(),
sendSubscribeMsgByPayType(order, orderName, "素材上传完成", DateUtils.sdf.format(order.getPayTime()),
order.getOrderNo(), orderTime, pageUrl); "",
} catch (Exception e) { pageUrl
log.error("素材上传通知发送失败,不影响主流程: orderNo={}", order.getOrderNo(), e); );
} }
} }
/** /**
* 订单完成后通知下一位用户 * 订单完成后通知下一位用户
* @param order
* @param tourism
*/ */
private void sendMessageToNextOrderUser(Order order, Tourism tourism) { private void sendMessageToNextOrderUser(Order order, Tourism tourism) {
try { // 新增:查找下一个排队用户
Order nextOrder = orderService.getNextQueueOrder(order.getTourismId(), order.getId()); Order nextOrder = orderService.getNextQueueOrder(order.getTourismId(), order.getId());
if (nextOrder != null && tourism != null) { if (nextOrder != null) {
String activityName = tourism.getTourismName(); SysUser nextUser = userCenterService.findUserById(nextOrder.getUserId());
if (nextUser != null && nextUser.getOpenId() != null && tourism != null) {
String activityName = tourism.getTourismName(); // 活动名称
String remark = "即将为您进行拍摄服务"; String remark = "即将为您进行拍摄服务";
String activityNo = nextOrder.getOrderNo(); String activityNo = nextOrder.getOrderNo(); // 活动编号
String pageUrl = "pages/album/album"; String pageUrl = "pages/album/album";
String orderTime = DateUtils.sdf.format(nextOrder.getPayTime()); wxMiniSubscribeService.sendServiceProcessMsg(
nextUser.getOpenId(),
sendSubscribeMsgByPayType(nextOrder, activityName, remark, activityName,
activityNo, orderTime, pageUrl); remark,
log.info("已通知下一个排队用户: userId={}, orderNo={}", nextOrder.getUserId(), activityNo); activityNo,
DateUtils.sdf.format(nextOrder.getPayTime()),
"",
pageUrl
);
log.info("已通知下一个排队用户: userId={}, openId={}, orderNo={}", nextUser.getId(), nextUser.getOpenId(), activityNo);
} }
} catch (Exception e) {
log.error("通知下一位排队用户失败,不影响主流程: orderNo={}", order.getOrderNo(), e);
} }
} }
@@ -302,35 +345,4 @@ public class OrderStatusChangeListener {
&& qrCode.getEnableVideoEdit() == 1 && qrCode.getEnableVideoEdit() == 1
&& qrCode.getTemplateId() != null; // 确保有模板ID && qrCode.getTemplateId() != null; // 确保有模板ID
} }
/**
* 根据订单支付类型发送小程序订阅消息
* payType=1 → 微信通知
* payType=4 → 支付宝通知
* 其他 → 不发送
*/
private void sendSubscribeMsgByPayType(Order order, String taskName, String processDesc,
String orderNo, String orderTime, String pageUrl) {
Integer payType = order.getPayType();
if (PayTypeEnum.WECHAT_PAY.getCode().equals(payType)) {
// 微信通知
SysUser sysUser = userCenterService.findUserById(order.getUserId());
if (sysUser != null && sysUser.getOpenId() != null) {
wxMiniSubscribeService.sendServiceProcessMsg(
sysUser.getOpenId(), taskName, processDesc,
orderNo, orderTime, "", pageUrl);
}
} else if (PayTypeEnum.ALIPAY_PAY.getCode().equals(payType)) {
// 支付宝通知:服务内部按 tenantId 查询 MINI 配置并获取 appId
if (order.getTenantId() != null && !order.getTenantId().isEmpty()) {
alipayMiniSubscribeService.sendServiceProcessMsg(
order.getUserId(), order.getTenantId(), taskName, processDesc,
orderNo, orderTime, pageUrl);
} else {
log.warn("订单 tenantId 为空,跳过支付宝订阅消息: orderNo={}", orderNo);
}
}
// payType=2(优惠券) / 3(核销) 不发送小程序通知
}
} }
@@ -1,25 +0,0 @@
package com.central.order.mapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.alipay.entity.AlipayConfig;
import com.central.db.mapper.SuperMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* 支付宝配置 Mapper
*
* @author duzhichao
* @date 2026-05-12
*/
@Mapper
public interface AlipayConfigMapper extends SuperMapper<AlipayConfig> {
/**
* 分页查询(支持按 type / tenantId / appId / status 筛选)
*/
List<AlipayConfig> findList(Page<AlipayConfig> page, @Param("p") Map<String, Object> params);
}
@@ -45,10 +45,6 @@ public interface OrderMapper extends SuperMapper<Order> {
// 根据订单编号查询订单信息 // 根据订单编号查询订单信息
Order getOrderByNumber(@Param("orderNumber") String orderNumber); Order getOrderByNumber(@Param("orderNumber") String orderNumber);
// 根据订单编号+租户ID查询订单信息(用于支付/退款回调严格隔离)
Order getOrderByNumberAndTenant(@Param("orderNumber") String orderNumber,
@Param("tenantId") String tenantId);
List<Order> findListByUser(Page<Order> page, @Param("p") Map<String, Object> params); List<Order> findListByUser(Page<Order> page, @Param("p") Map<String, Object> params);
@Select("SELECT \n" + @Select("SELECT \n" +
@@ -1,25 +0,0 @@
package com.central.order.mission.VO;
import lombok.Data;
/**
* 指点飞行(首次飞向目标)Feign 请求 VO
*
* @author dzc
* @date 2026-01-23
*/
@Data
public class FlyToPointRequestVO {
/** 设备SN */
private String deviceSn;
/** 飞行会话ID(= missionCode) */
private String flyToId;
/** 目标纬度 */
private Double latitude;
/** 目标经度 */
private Double longitude;
/** 目标椭球高 */
private Float height;
/** 最大飞行速度(m/s),默认 12 */
private Float maxSpeed;
}
@@ -1,24 +0,0 @@
package com.central.order.mission.VO;
import lombok.Data;
/**
* 指点飞行更新目标(连续指点)Feign 请求 VO
* 注意:设备协议不含 fly_to_id,仅传 max_speed + points
*
* @author dzc
* @date 2026-01-23
*/
@Data
public class FlyToPointUpdateRequestVO {
/** 设备SN */
private String deviceSn;
/** 目标纬度 */
private Double latitude;
/** 目标经度 */
private Double longitude;
/** 目标椭球高 */
private Float height;
/** 最大飞行速度(m/s),默认 12 */
private Float maxSpeed;
}
@@ -1,30 +0,0 @@
package com.central.order.mission.command;
import lombok.Builder;
import lombok.Data;
/**
* 指点飞行目标下发参数。
*/
@Data
@Builder
public class FlyToPointTargetCommand {
private Double latitude;
private Double longitude;
private Float height;
private Float maxSpeed;
private String clearanceStatus;
private Float clearanceMeters;
private Float candidateSurfaceHeight;
private boolean riskAcknowledged;
private String riskReason;
private Long riskAcknowledgedUserId;
private String riskAcknowledgedUsername;
public void validateRiskAcknowledgement() {
if (!"VERIFIED".equals(clearanceStatus) && !riskAcknowledged) {
throw new IllegalArgumentException("路径净空未验证,请确认风险后再发送目标");
}
}
}
@@ -1,34 +0,0 @@
package com.central.order.mission.command;
import lombok.Data;
/**
* 指点飞行目标更新接口请求。
*/
@Data
public class FlyToPointUpdateRequest {
private String missionCode;
private Double latitude;
private Double longitude;
private Float height;
private Float maxSpeed;
private String clearanceStatus;
private Float clearanceMeters;
private Float candidateSurfaceHeight;
private Boolean riskAcknowledged;
private String riskReason;
public FlyToPointTargetCommand toCommand() {
return FlyToPointTargetCommand.builder()
.latitude(latitude)
.longitude(longitude)
.height(height)
.maxSpeed(maxSpeed == null ? 12f : maxSpeed)
.clearanceStatus(clearanceStatus == null ? "UNVERIFIED" : clearanceStatus)
.clearanceMeters(clearanceMeters)
.candidateSurfaceHeight(candidateSurfaceHeight)
.riskAcknowledged(Boolean.TRUE.equals(riskAcknowledged))
.riskReason(riskReason)
.build();
}
}
@@ -8,8 +8,6 @@ import com.central.common.model.Result;
import com.central.order.feign.FileCenterService; import com.central.order.feign.FileCenterService;
import com.central.order.mission.enums.MissionStatus; import com.central.order.mission.enums.MissionStatus;
import com.central.order.mission.enums.MissionType; import com.central.order.mission.enums.MissionType;
import com.central.order.mission.command.FlyToPointTargetCommand;
import com.central.order.mission.command.FlyToPointUpdateRequest;
import com.central.order.mission.model.Mission; import com.central.order.mission.model.Mission;
import com.central.order.mission.model.MissionImage; import com.central.order.mission.model.MissionImage;
import com.central.order.mission.service.IMissionImageService; import com.central.order.mission.service.IMissionImageService;
@@ -281,115 +279,6 @@ public class MissionController {
} }
} }
// ==================== 指点飞行编排接口 ====================
/**
* 开始指点飞行
*/
@Operation(summary = "开始指点飞行")
@PostMapping("/startFlyToPoint")
public Result<Map<String, Object>> startFlyToPoint(@RequestBody Map<String, Object> params) {
try {
TenantContextHolder.setTenant("webApp");
String deviceSn = (String) params.get("deviceSn");
if (!StringUtils.hasText(deviceSn)) {
return Result.failed("设备SN不能为空");
}
Double dockLatitude = params.get("dockLatitude") != null ?
Double.parseDouble(params.get("dockLatitude").toString()) : null;
Double dockLongitude = params.get("dockLongitude") != null ?
Double.parseDouble(params.get("dockLongitude").toString()) : null;
Float dockHeight = params.get("dockHeight") != null ?
Float.parseFloat(params.get("dockHeight").toString()) : null;
Boolean isAirborne = params.get("isAirborne") != null ?
(Boolean) params.get("isAirborne") : false;
String missionCode = missionService.startFlyToPoint(deviceSn, dockLatitude, dockLongitude, dockHeight, isAirborne);
Map<String, Object> result = new HashMap<>();
result.put("missionCode", missionCode);
return Result.succeed(result, "指点飞行任务已开始");
} catch (Exception e) {
log.error("开始指点飞行异常", e);
return Result.failed("开始指点飞行失败: " + e.getMessage());
} finally {
TenantContextHolder.clear();
}
}
/**
* 更新指点飞行目标点
*/
@Operation(summary = "更新指点飞行目标点")
@PostMapping("/flyToPointUpdate")
public Result<String> flyToPointUpdate(@RequestBody FlyToPointUpdateRequest request) {
try {
TenantContextHolder.setTenant("webApp");
String missionCode = request.getMissionCode();
if (!StringUtils.hasText(missionCode)) {
return Result.failed("任务编码不能为空");
}
FlyToPointTargetCommand command = request.toCommand();
// 第一版没有服务端路径净空验证能力,不能信任客户端声明“已验证”。
command.setClearanceStatus("UNVERIFIED");
if (command.getLatitude() == null || command.getLongitude() == null || command.getHeight() == null) {
return Result.failed("目标经纬度和高度不能为空");
}
if (command.getLatitude() < -90 || command.getLatitude() > 90
|| command.getLongitude() < -180 || command.getLongitude() > 180) {
return Result.failed("目标经纬度不合法");
}
LoginAppUser user = LoginUserContextHolder.getUser();
if (user == null) {
return Result.failed("用户未登录,无法确认飞行风险");
}
command.setRiskAcknowledgedUserId(user.getId());
command.setRiskAcknowledgedUsername(user.getUsername());
command.validateRiskAcknowledgement();
missionService.flyToPointUpdate(missionCode, command);
return Result.succeed("目标点已更新");
} catch (Exception e) {
log.error("更新指点飞行目标点异常", e);
return Result.failed("更新目标点失败: " + e.getMessage());
} finally {
TenantContextHolder.clear();
}
}
/**
* 结束指点飞行
*/
@Operation(summary = "结束指点飞行")
@PostMapping("/endFlyToPoint")
public Result<String> endFlyToPoint(@RequestBody Map<String, Object> params) {
try {
TenantContextHolder.setTenant("webApp");
String missionCode = (String) params.get("missionCode");
if (!StringUtils.hasText(missionCode)) {
return Result.failed("任务编码不能为空");
}
missionService.endFlyToPoint(missionCode);
return Result.succeed("指点飞行已结束,返航中");
} catch (Exception e) {
log.error("结束指点飞行异常", e);
return Result.failed("结束指点飞行失败: " + e.getMessage());
} finally {
TenantContextHolder.clear();
}
}
/** /**
* 获取当前登录人的任务及图片列表 * 获取当前登录人的任务及图片列表
*/ */
@@ -13,8 +13,7 @@ import lombok.Getter;
public enum MissionType implements ZltEnum { public enum MissionType implements ZltEnum {
WAYLINE(1, "航线任务"), WAYLINE(1, "航线任务"),
TAKEOFF(2, "一键起飞任务"), TAKEOFF(2, "一键起飞任务"),
BOAT_ROUTE(3, "无人船航线任务"), BOAT_ROUTE(3, "无人船航线任务");
FLY_TO_POINT(4, "指点飞行任务");
MissionType(Integer id, String content) { MissionType(Integer id, String content) {
this.id = id; this.id = id;
@@ -59,11 +58,4 @@ public enum MissionType implements ZltEnum {
public static boolean isBoatRouteTask(Integer type) { public static boolean isBoatRouteTask(Integer type) {
return type != null && type.equals(BOAT_ROUTE.getId()); return type != null && type.equals(BOAT_ROUTE.getId());
} }
/**
* 判断是否为指点飞行任务
*/
public static boolean isFlyToPointTask(Integer type) {
return type != null && type.equals(FLY_TO_POINT.getId());
}
} }
@@ -1,9 +0,0 @@
package com.central.order.mission.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.order.mission.model.MissionFlyToPoint;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface MissionFlyToPointMapper extends BaseMapper<MissionFlyToPoint> {
}
@@ -34,11 +34,6 @@ public interface MissionMapper extends BaseMapper<Mission> {
*/ */
Mission getByMissionCode(@Param("missionCode") String missionCode); Mission getByMissionCode(@Param("missionCode") String missionCode);
/**
* 锁定任务行,串行化同一指点飞行会话的目标更新。
*/
Mission getByMissionCodeForUpdate(@Param("missionCode") String missionCode);
/** /**
* 更新任务状态 * 更新任务状态
* *
@@ -108,7 +108,4 @@ public class Mission extends SuperEntity {
@Schema(description = "任务状态描述") @Schema(description = "任务状态描述")
@TableField(exist = false) @TableField(exist = false)
private transient String missionStatusDesc; private transient String missionStatusDesc;
@Schema(description = "会话阶段:ACTIVE / RETURNING")
private String phase;
} }
@@ -1,32 +0,0 @@
package com.central.order.mission.model;
import com.baomidou.mybatisplus.annotation.TableName;
import com.central.common.model.SuperEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 指点飞行每次下发目标及风险确认审计记录。
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("mission_fly_to_point")
public class MissionFlyToPoint extends SuperEntity {
private String missionCode;
private String flyToId;
private String commandId;
private Integer seq;
private String commandType;
private Double latitude;
private Double longitude;
private Float height;
private Float maxSpeed;
private String status;
private String clearanceStatus;
private Float clearanceMeters;
private Float candidateSurfaceHeight;
private Integer riskAcknowledged;
private String riskReason;
private Long riskAcknowledgedUserId;
private String riskAcknowledgedUsername;
}
@@ -4,7 +4,6 @@ import com.baomidou.mybatisplus.extension.service.IService;
import com.central.common.model.PageResult; import com.central.common.model.PageResult;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.order.mission.model.Mission; import com.central.order.mission.model.Mission;
import com.central.order.mission.command.FlyToPointTargetCommand;
import java.util.Map; import java.util.Map;
@@ -97,36 +96,4 @@ public interface IMissionService extends IService<Mission> {
* @return 下发成功返回true * @return 下发成功返回true
*/ */
boolean dispatchMissionToDevice(Mission mission); boolean dispatchMissionToDevice(Mission mission);
// ==================== 指点飞行编排接口 ====================
/**
* 开始指点飞行
*
* @param deviceSn 设备SN
* @param dockLatitude 机库纬度
* @param dockLongitude 机库经度
* @param dockHeight 机库高度
* @param isAirborne 是否已升空(前端 SSE 判断)
* @return 任务编码
*/
String startFlyToPoint(String deviceSn, Double dockLatitude, Double dockLongitude, Float dockHeight, boolean isAirborne);
/**
* 更新指点飞行目标点
*
* @param missionCode 任务编码
* @param latitude 目标纬度
* @param longitude 目标经度
* @param height 目标椭球高
* @param maxSpeed 最大速度
*/
void flyToPointUpdate(String missionCode, FlyToPointTargetCommand command);
/**
* 结束指点飞行
*
* @param missionCode 任务编码
*/
void endFlyToPoint(String missionCode);
} }
@@ -6,14 +6,10 @@ import com.central.common.model.PageResult;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.order.feign.DeviceCenterService; import com.central.order.feign.DeviceCenterService;
import com.central.order.mission.VO.TakeoffRequestVO; import com.central.order.mission.VO.TakeoffRequestVO;
import com.central.order.mission.VO.FlyToPointRequestVO;
import com.central.order.mission.command.FlyToPointTargetCommand;
import com.central.order.mission.enums.MissionStatus; import com.central.order.mission.enums.MissionStatus;
import com.central.order.mission.enums.MissionType; import com.central.order.mission.enums.MissionType;
import com.central.order.mission.mapper.MissionMapper; import com.central.order.mission.mapper.MissionMapper;
import com.central.order.mission.mapper.MissionFlyToPointMapper;
import com.central.order.mission.model.Mission; import com.central.order.mission.model.Mission;
import com.central.order.mission.model.MissionFlyToPoint;
import com.central.order.mission.service.IMissionService; import com.central.order.mission.service.IMissionService;
import com.central.order.weather.model.WeatherCheckResult; import com.central.order.weather.model.WeatherCheckResult;
import com.central.order.weather.service.IWeatherRuleValidator; import com.central.order.weather.service.IWeatherRuleValidator;
@@ -42,9 +38,6 @@ public class MissionServiceImpl extends ServiceImpl<MissionMapper, Mission> impl
@Resource @Resource
DeviceCenterService deviceCenterService; DeviceCenterService deviceCenterService;
@Resource
MissionFlyToPointMapper missionFlyToPointMapper;
@Autowired @Autowired
private IWeatherRuleValidator weatherRuleValidator; private IWeatherRuleValidator weatherRuleValidator;
@@ -256,13 +249,6 @@ public class MissionServiceImpl extends ServiceImpl<MissionMapper, Mission> impl
@Override @Override
public boolean dispatchMissionToDevice(Mission mission) { public boolean dispatchMissionToDevice(Mission mission) {
return dispatchMissionToDevice(mission, false);
}
/**
* 下发任务到设备(带升空状态)
*/
public boolean dispatchMissionToDevice(Mission mission, boolean isAirborne) {
try { try {
Integer missionType = mission.getMissionType(); Integer missionType = mission.getMissionType();
@@ -325,33 +311,6 @@ public class MissionServiceImpl extends ServiceImpl<MissionMapper, Mission> impl
log.error("无人船航线任务下发失败: missionCode={}, error={}", mission.getMissionCode(), errorMsg); log.error("无人船航线任务下发失败: missionCode={}, error={}", mission.getMissionCode(), errorMsg);
return false; return false;
} }
} else if (MissionType.isFlyToPointTask(missionType)) {
// 指点飞行任务:前端 SSE 判断是否已升空
log.info("下发指点飞行任务到设备: missionCode={}, deviceSn={}, isAirborne={}",
mission.getMissionCode(), mission.getDeviceSn(), isAirborne);
if (!isAirborne) {
// 未升空 → 先起飞
TakeoffRequestVO takeoffRequestVO = new TakeoffRequestVO();
takeoffRequestVO.setTargetHeight(mission.getTargetHeight() != null ? mission.getTargetHeight().floatValue() : 20f);
takeoffRequestVO.setDeviceSn(mission.getDeviceSn());
takeoffRequestVO.setFlightId(mission.getMissionCode());
takeoffRequestVO.setTargetLatitude(mission.getTargetLatitude() != null ? mission.getTargetLatitude().doubleValue() : 0d);
takeoffRequestVO.setTargetLongitude(mission.getTargetLongitude() != null ? mission.getTargetLongitude().doubleValue() : 0d);
Result<String> takeoffResult = deviceCenterService.takeoff(takeoffRequestVO);
if (takeoffResult == null || takeoffResult.getResp_code() != 0) {
log.error("指点飞行起飞命令失败: missionCode={}", mission.getMissionCode());
return false;
}
log.info("指点飞行起飞命令已发送: missionCode={}", mission.getMissionCode());
} else {
log.info("无人机已升空,跳过起飞步骤: missionCode={}", mission.getMissionCode());
}
// 命令入队成功 → 任务状态为 DOING
updateMissionStatus(mission.getMissionCode(), MissionStatus.DOING.getId());
return true;
} else { } else {
log.error("未知的任务类型: {}", missionType); log.error("未知的任务类型: {}", missionType);
return false; return false;
@@ -362,188 +321,4 @@ public class MissionServiceImpl extends ServiceImpl<MissionMapper, Mission> impl
return false; return false;
} }
} }
// ==================== 指点飞行编排方法 ====================
@Override
@Transactional(rollbackFor = Exception.class)
public String startFlyToPoint(String deviceSn, Double dockLatitude, Double dockLongitude, Float dockHeight, boolean isAirborne) {
log.info("开始指点飞行: deviceSn={}, dock=({}, {}, {})", deviceSn, dockLatitude, dockLongitude, dockHeight);
// 1. 创建 FLY_TO_POINT 任务
Mission mission = new Mission();
mission.setDeviceSn(deviceSn);
mission.setMissionType(MissionType.FLY_TO_POINT.getId());
mission.setMissionName("指点飞行任务");
mission.setMissionStatus(MissionStatus.PENDING.getId());
mission.setTargetLatitude(dockLatitude != null ? java.math.BigDecimal.valueOf(dockLatitude) : null);
mission.setTargetLongitude(dockLongitude != null ? java.math.BigDecimal.valueOf(dockLongitude) : null);
mission.setTargetHeight(java.math.BigDecimal.valueOf(20));
mission.setPhase("ACTIVE");
String missionCode = generateMissionCode();
mission.setMissionCode(missionCode);
save(mission);
log.info("指点飞行任务已创建: missionCode={}", missionCode);
// 2. 执行任务(dispatchMissionToDevice 会处理起飞逻辑)
boolean dispatched = dispatchMissionToDevice(mission, isAirborne);
if (!dispatched) {
log.error("指点飞行任务下发失败: missionCode={}", missionCode);
throw new RuntimeException("任务下发失败");
}
return missionCode;
}
@Override
@Transactional(rollbackFor = Exception.class)
public void flyToPointUpdate(String missionCode, FlyToPointTargetCommand command) {
command.validateRiskAcknowledgement();
Double latitude = command.getLatitude();
Double longitude = command.getLongitude();
Float height = command.getHeight();
Float maxSpeed = command.getMaxSpeed();
log.info("更新指点飞行目标: missionCode={}, target=({}, {}, {})", missionCode, latitude, longitude, height);
Mission mission = baseMapper.getByMissionCodeForUpdate(missionCode);
if (mission == null) {
throw new RuntimeException("任务不存在: " + missionCode);
}
// 校验状态
if (!MissionStatus.DOING.getId().equals(mission.getMissionStatus())) {
throw new RuntimeException("任务状态不允许更新目标: " + mission.getMissionStatus());
}
if (!"ACTIVE".equals(mission.getPhase())) {
throw new RuntimeException("飞行已结束,无法更新目标");
}
String deviceSn = mission.getDeviceSn();
// 判断是否首次指点:查询 mission_fly_to_point 子表
boolean isFirstTarget = !hasSentFirstFlyToPoint(missionCode);
Result<String> result;
String commandType;
if (isFirstTarget) {
FlyToPointRequestVO requestVO = new FlyToPointRequestVO();
requestVO.setDeviceSn(deviceSn);
requestVO.setFlyToId(missionCode);
requestVO.setLatitude(latitude);
requestVO.setLongitude(longitude);
requestVO.setHeight(height);
requestVO.setMaxSpeed(maxSpeed != null ? maxSpeed : 12f);
result = deviceCenterService.flyToPoint(requestVO);
if (result == null || result.getResp_code() != 0) {
throw new RuntimeException("指点飞行命令失败: " + (result != null ? result.getResp_msg() : "无响应"));
}
commandType = "fly_to_point";
log.info("首次指点飞行命令已发送: missionCode={}, commandId={}", missionCode, result.getData());
} else {
// 设备端不支持 fly_to_point_update,连续改飞复用 fly_to_point 并沿用同一会话标识。
FlyToPointRequestVO requestVO = new FlyToPointRequestVO();
requestVO.setDeviceSn(deviceSn);
requestVO.setFlyToId(missionCode);
requestVO.setLatitude(latitude);
requestVO.setLongitude(longitude);
requestVO.setHeight(height);
requestVO.setMaxSpeed(maxSpeed != null ? maxSpeed : 12f);
result = deviceCenterService.flyToPoint(requestVO);
if (result == null || result.getResp_code() != 0) {
throw new RuntimeException("目标更新命令失败: " + (result != null ? result.getResp_msg() : "无响应"));
}
commandType = "fly_to_point";
log.info("目标更新命令已发送: missionCode={}, commandId={}", missionCode, result.getData());
}
MissionFlyToPoint record = new MissionFlyToPoint();
record.setMissionCode(missionCode);
record.setFlyToId(missionCode);
record.setCommandId(result.getData());
record.setSeq(nextTargetSequence(missionCode));
record.setCommandType(commandType);
record.setLatitude(latitude);
record.setLongitude(longitude);
record.setHeight(height);
record.setMaxSpeed(maxSpeed != null ? maxSpeed : 12f);
record.setStatus("SENT");
record.setClearanceStatus(command.getClearanceStatus());
record.setClearanceMeters(command.getClearanceMeters());
record.setCandidateSurfaceHeight(command.getCandidateSurfaceHeight());
record.setRiskAcknowledged(command.isRiskAcknowledged() ? 1 : 0);
record.setRiskReason(command.getRiskReason());
record.setRiskAcknowledgedUserId(command.getRiskAcknowledgedUserId());
record.setRiskAcknowledgedUsername(command.getRiskAcknowledgedUsername());
missionFlyToPointMapper.insert(record);
mission.setTargetLatitude(java.math.BigDecimal.valueOf(latitude));
mission.setTargetLongitude(java.math.BigDecimal.valueOf(longitude));
mission.setTargetHeight(java.math.BigDecimal.valueOf(height));
updateById(mission);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void endFlyToPoint(String missionCode) {
log.info("结束指点飞行: missionCode={}", missionCode);
Mission mission = baseMapper.getByMissionCodeForUpdate(missionCode);
if (mission == null) {
throw new RuntimeException("任务不存在: " + missionCode);
}
// 校验状态
if (!MissionStatus.DOING.getId().equals(mission.getMissionStatus())) {
throw new RuntimeException("任务状态不允许结束: " + mission.getMissionStatus());
}
if (!"ACTIVE".equals(mission.getPhase())) {
log.warn("任务已处于返航状态,忽略重复结束请求: missionCode={}", missionCode);
return;
}
String deviceSn = mission.getDeviceSn();
// 1. 原子更新 phase = RETURNING(防止并发更新目标)
mission.setPhase("RETURNING");
updateById(mission);
// 2. 设备端不支持 fly_to_point_stop,直接发送一键返航命令。
Result<String> returnResult = deviceCenterService.returnHome(deviceSn);
// 返航命令失败不会阻塞流程(phase 保持 RETURNING)
if (returnResult == null || returnResult.getResp_code() != 0) {
log.error("返航命令失败,任务保持 RETURNING: missionCode={}", missionCode);
throw new RuntimeException("返航命令失败,任务未结束: " + (returnResult != null ? returnResult.getResp_msg() : "无响应"));
}
log.info("指点飞行结束流程完成,等待降落: missionCode={}", missionCode);
}
/**
* 判断是否已发送过首次 fly_to_point 指令
*/
private boolean hasSentFirstFlyToPoint(String missionCode) {
return missionFlyToPointMapper.selectCount(
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<MissionFlyToPoint>()
.eq(MissionFlyToPoint::getMissionCode, missionCode)
.eq(MissionFlyToPoint::getCommandType, "fly_to_point")) > 0;
}
private int nextTargetSequence(String missionCode) {
Long count = missionFlyToPointMapper.selectCount(
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<MissionFlyToPoint>()
.eq(MissionFlyToPoint::getMissionCode, missionCode));
return count.intValue() + 1;
}
/**
* 生成任务编码
*/
private String generateMissionCode() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
return "FP" + sdf.format(new Date());
}
} }
@@ -38,7 +38,7 @@ public class Order extends SuperEntity {
@Schema(description = "订单状态") @Schema(description = "订单状态")
private Integer orderStatus; private Integer orderStatus;
@Schema(description = "支付类型(1:微信支付,2:优惠券支付,3:第三方聚到核销,4:支付宝支付)") @Schema(description = "支付类型(1:微信支付,2:优惠券支付, 3: 第三方聚到核销)")
private Integer payType; private Integer payType;
private Date payTime; private Date payTime;
@@ -132,22 +132,4 @@ public class QrCode extends SuperEntity {
@Schema(description = "携程产品ID") @Schema(description = "携程产品ID")
private Long ctripProductId; private Long ctripProductId;
/**
* 支付宝小程序二维码 fileId(S3)
*/
@Schema(description = "支付宝小程序二维码 fileId(S3)")
private String alipayFileId;
/**
* 支付宝小程序二维码对象路径(S3 bucket/objectKey)
*/
@Schema(description = "支付宝小程序二维码对象路径(S3 bucket/objectKey)")
private String alipayFilePath;
/**
* 支付宝小程序二维码访问 URL(运行时填充,不入库)
*/
@Schema(description = "支付宝小程序二维码访问 URL(运行时填充,不入库)")
private transient String alipayViewUrl;
} }
@@ -1,29 +0,0 @@
package com.central.order.service;
/**
* 支付宝小程序订阅消息服务
* <p>
* 对标 WxMiniSubscribeService,封装支付宝模板消息发送能力。
* 支持通过系统 userId + 租户ID 自动查询支付宝 userId 并发送消息。
*
* @author duzhichao
* @date 2026-06-24
*/
public interface AlipayMiniSubscribeService {
/**
* 发送服务进度通知(支付成功/退款中/退款完成/排队通知等)
*
* @param userId 系统用户ID
* @param tenantId 租户ID,用于查询 type=MINI 的支付宝小程序配置
* @param taskName 服务名称(如景区名称)
* @param processDesc 服务阶段描述(如"支付成功,当前排第2位")
* @param orderNo 订单编号
* @param orderTime 下单时间
* @param pageUrl 跳转小程序页面路径
*/
void sendServiceProcessMsg(Long userId, String tenantId,
String taskName, String processDesc,
String orderNo, String orderTime,
String pageUrl);
}
@@ -1,56 +0,0 @@
package com.central.order.service;
import com.central.alipay.entity.AlipayConfig;
import com.central.common.model.PageResult;
import com.central.common.service.ISuperService;
import java.util.Map;
/**
* 支付宝配置 Service 接口
*
* @author duzhichao
* @date 2026-05-12
*/
public interface IAlipayConfigService extends ISuperService<AlipayConfig> {
/**
* 分页查询
*/
PageResult<AlipayConfig> findList(Map<String, Object> params);
/**
* 根据类型和租户ID查询配置
*/
AlipayConfig getConfigByTypeAndTenantId(String type, String tenantId);
/**
* 根据 AppId 和类型查询配置
*/
AlipayConfig getConfigByAppIdAndType(String appId, String type);
/**
* 根据 AppId 查询配置(不区分类型)
*/
AlipayConfig getConfigByAppId(String appId);
/**
* 根据子商户号查询配置(ISV 模式)
*/
AlipayConfig getConfigBySubMerchantId(String subMerchantId);
/**
* 保存配置
*/
boolean saveConfig(AlipayConfig config);
/**
* 更新配置
*/
boolean updateConfig(AlipayConfig config);
/**
* 删除配置
*/
boolean deleteConfig(Long id);
}
@@ -14,12 +14,4 @@ public interface ICtripDistOrderService {
* @param mobile 用户手机号(可为null,为null时使用默认值) * @param mobile 用户手机号(可为null,为null时使用默认值)
*/ */
void createCtripDistOrder(String orderNo, String orderAmount, Long ctripProductId, String tenantId, String mobile); void createCtripDistOrder(String orderNo, String orderAmount, Long ctripProductId, String tenantId, String mobile);
/**
* 异步退订携程分销订单
*
* @param orderNo 本地订单号
* @param reason 退订原因
*/
void cancelCtripDistOrder(String orderNo, String reason);
} }
@@ -57,17 +57,6 @@ public interface IOrderService extends ISuperService<Order> {
*/ */
Order getOrderByNumber(String orderNumber); Order getOrderByNumber(String orderNumber);
/**
* 订单编号+租户ID 查询订单(支付/退款回调严格隔离)
*/
Order getOrderByNumberAndTenant(String orderNumber, String tenantId);
/**
* 订单编号查询订单(优先按租户查询,查不到则降级仅按订单号查询)
* 用于支付宝回调等场景,配置租户可能与订单租户不一致的情况
*/
Order getOrderByNumberWithFallback(String orderNumber, String tenantId);
/** /**
* 订单信息更新 * 订单信息更新
* @param order * @param order
@@ -1,103 +0,0 @@
package com.central.order.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.alipay.entity.AlipayConfig;
import com.central.common.model.PageResult;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.order.mapper.AlipayConfigMapper;
import com.central.order.service.IAlipayConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Map;
/**
* 支付宝配置 Service 实现
*
* @author duzhichao
* @date 2026-05-12
*/
@Slf4j
@Service
public class AlipayConfigServiceImpl
extends SuperServiceImpl<AlipayConfigMapper, AlipayConfig>
implements IAlipayConfigService {
@Override
public PageResult<AlipayConfig> findList(Map<String, Object> params) {
Page<AlipayConfig> page = new Page<>(
MapUtils.getInteger(params, "page", 1),
MapUtils.getInteger(params, "limit", 10));
List<AlipayConfig> list = baseMapper.findList(page, params);
return PageResult.<AlipayConfig>builder()
.data(list).resp_code(0).count(page.getTotal()).build();
}
@Override
public AlipayConfig getConfigByTypeAndTenantId(String type, String tenantId) {
// 1. 先按当前租户查询
AlipayConfig config = queryByTypeAndTenantId(type, tenantId);
if (config != null) {
return config;
}
// 2. 查不到时降级到 webApp 默认配置
if (!"webApp".equals(tenantId)) {
log.info("当前租户[{}]未配置支付宝[{}],降级使用 webApp 默认配置", tenantId, type);
config = queryByTypeAndTenantId(type, "webApp");
}
return config;
}
private AlipayConfig queryByTypeAndTenantId(String type, String tenantId) {
LambdaQueryWrapper<AlipayConfig> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(AlipayConfig::getType, type)
.eq(AlipayConfig::getTenantId, tenantId)
.eq(AlipayConfig::getStatus, 1);
return baseMapper.selectOne(wrapper);
}
@Override
public AlipayConfig getConfigByAppIdAndType(String appId, String type) {
LambdaQueryWrapper<AlipayConfig> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(AlipayConfig::getAppId, appId)
.eq(AlipayConfig::getType, type)
.eq(AlipayConfig::getStatus, 1);
return baseMapper.selectOne(wrapper);
}
@Override
public AlipayConfig getConfigByAppId(String appId) {
LambdaQueryWrapper<AlipayConfig> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(AlipayConfig::getAppId, appId)
.eq(AlipayConfig::getStatus, 1)
.last("LIMIT 1");
return baseMapper.selectOne(wrapper);
}
@Override
public AlipayConfig getConfigBySubMerchantId(String subMerchantId) {
LambdaQueryWrapper<AlipayConfig> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(AlipayConfig::getSubMerchantId, subMerchantId)
.eq(AlipayConfig::getStatus, 1);
return baseMapper.selectOne(wrapper);
}
@Override
public boolean saveConfig(AlipayConfig config) {
return save(config);
}
@Override
public boolean updateConfig(AlipayConfig config) {
return updateById(config);
}
@Override
public boolean deleteConfig(Long id) {
return removeById(id);
}
}
@@ -1,219 +0,0 @@
package com.central.order.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayObject;
import com.alipay.api.AlipayRequest;
import com.alipay.api.AlipayResponse;
import com.alipay.api.internal.util.AlipaySignature;
import com.central.alipay.config.AlipayClientFactory;
import com.central.alipay.entity.AlipayConfig;
import com.central.common.feign.UserService;
import com.central.order.service.AlipayMiniSubscribeService;
import com.central.order.service.IAlipayConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* 支付宝小程序订阅消息服务实现
* <p>
* 通过 {@link AlipayClient(AlipayRequest, Map)} 直接调用
* alipay.open.app.message.subscription.send 接口,无需依赖特定 SDK 版本的 Request/Response 类。
* <p>
* 验证方式、参数签名等均由 AlipayClient 统一处理。
*
* @author duzhichao
* @date 2026-06-24
*/
@Slf4j
@Service
public class AlipayMiniSubscribeServiceImpl implements AlipayMiniSubscribeService {
/** 支付宝小程序订阅消息发送接口方法名 */
private static final String API_METHOD = "alipay.open.app.message.subscription.send";
@Value("${alipay.mini.template.service-process:}")
private String serviceProcessTemplateId;
@Autowired
private AlipayClientFactory alipayClientFactory;
@Autowired
private IAlipayConfigService alipayConfigService;
@Autowired
private UserService userService;
@Override
public void sendServiceProcessMsg(Long userId, String tenantId,
String taskName, String processDesc,
String orderNo, String orderTime,
String pageUrl) {
try {
// 0. 校验模板ID配置
if (serviceProcessTemplateId == null || serviceProcessTemplateId.isEmpty()) {
log.warn("支付宝小程序订阅消息模板ID未配置(alipay.mini.template.service-process),跳过通知: orderNo={}", orderNo);
return;
}
// 1. 按租户获取支付宝小程序配置(type=MINI)
AlipayConfig config = alipayConfigService.getConfigByTypeAndTenantId("MINI", tenantId);
if (config == null) {
log.warn("支付宝小程序配置不存在(type=MINI),跳过通知: tenantId={}, orderNo={}", tenantId, orderNo);
return;
}
String appId = config.getAppId();
if (appId == null || appId.isEmpty()) {
log.warn("支付宝小程序 appId 为空,跳过通知: tenantId={}, orderNo={}", tenantId, orderNo);
return;
}
// 2. 通过 userId + appId 反查支付宝 userId
String alipayUserId = userService.getAlipayOpenIdByUserId(userId, appId);
if (alipayUserId == null || alipayUserId.isEmpty()) {
log.warn("用户无支付宝 userId,跳过通知: userId={}, appId={}, orderNo={}", userId, appId, orderNo);
return;
}
// 3. 获取支付宝客户端(MINI 类型配置)
AlipayClient client = alipayClientFactory.createAlipayClient(config);
// 4. 构建订阅消息参数(字段名需与支付宝开放平台申请的模板变量一致)
JSONObject data = new JSONObject();
data.put("taskName", new JSONObject().put("value", taskName != null ? taskName : ""));
data.put("processDesc", new JSONObject().put("value", processDesc != null ? processDesc : ""));
data.put("orderNo", new JSONObject().put("value", orderNo != null ? orderNo : ""));
data.put("orderTime", new JSONObject().put("value", orderTime != null ? orderTime : ""));
JSONObject bizContent = new JSONObject();
bizContent.put("to_user_id", alipayUserId);
bizContent.put("template_id", serviceProcessTemplateId);
if (pageUrl != null && !pageUrl.isEmpty()) {
bizContent.put("page", pageUrl);
}
bizContent.put("data", data);
// 5. 使用 AlipayRequest 接口直接调用,无需依赖特定 SDK 版本的 Request 类
Map<String, String> requestParams = new HashMap<>();
requestParams.put("method", API_METHOD);
requestParams.put("biz_content", bizContent.toJSONString());
AlipayRequest<AlipayResponse> request = new SimpleAlipayRequest(requestParams);
// 6. 发送
AlipayResponse response = client.execute(request);
if (response.isSuccess()) {
log.info("支付宝小程序订阅消息发送成功: userId={}, orderNo={}, templateId={}",
userId, orderNo, serviceProcessTemplateId);
} else {
log.error("支付宝小程序订阅消息发送失败: userId={}, orderNo={}, subCode={}, subMsg={}",
userId, orderNo, response.getSubCode(), response.getSubMsg());
}
} catch (Exception e) {
// 支付宝消息发送失败不影响主业务流程
log.error("支付宝小程序订阅消息发送异常: userId={}, orderNo={}", userId, orderNo, e);
}
}
/**
* 简易 AlipayRequest 实现,通过 Map 传参,避免依赖特定 SDK 版本的 Request 类。
* <p>
* 方法签名严格对齐 alipay-sdk-java 4.40.816.ALL 中 AlipayRequest 接口的 19 个抽象方法。
*/
private static class SimpleAlipayRequest implements AlipayRequest<AlipayResponse> {
private final Map<String, String> requestParams;
SimpleAlipayRequest(Map<String, String> requestParams) {
this.requestParams = requestParams;
}
// ---- AlipayRequest 接口 19 个抽象方法(按 javap 反编译顺序) ----
@Override
public String getApiMethodName() {
return requestParams.get("method");
}
@Override
public Map<String, String> getTextParams() {
return requestParams;
}
@Override
public String getApiVersion() {
return "1.0";
}
@Override
public void setApiVersion(String apiVersion) { }
@Override
public String getTerminalType() {
return null;
}
@Override
public void setTerminalType(String terminalType) { }
@Override
public String getTerminalInfo() {
return null;
}
@Override
public void setTerminalInfo(String terminalInfo) { }
@Override
public String getProdCode() {
return null;
}
@Override
public void setProdCode(String prodCode) { }
@Override
public String getNotifyUrl() {
return null;
}
@Override
public void setNotifyUrl(String notifyUrl) { }
@Override
public String getReturnUrl() {
return null;
}
@Override
public void setReturnUrl(String returnUrl) { }
@Override
public Class<AlipayResponse> getResponseClass() {
return AlipayResponse.class;
}
@Override
public boolean isNeedEncrypt() {
return false;
}
@Override
public void setNeedEncrypt(boolean needEncrypt) { }
@Override
public AlipayObject getBizModel() {
return null;
}
@Override
public void setBizModel(AlipayObject bizModel) { }
}
}
@@ -41,20 +41,4 @@ public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
log.error("携程分销订单创建异常,orderNo: {}", orderNo, e); log.error("携程分销订单创建异常,orderNo: {}", orderNo, e);
} }
} }
@Async
@Override
public void cancelCtripDistOrder(String orderNo, String reason) {
log.info("开始异步退订携程分销订单,orderNo: {}, reason: {}", orderNo, reason);
try {
Result<String> result = couponCenterService.cancelCtripDistOrder(orderNo, reason);
if (result != null && result.getResp_code() == 0) {
log.info("携程分销订单退订成功,orderNo: {}", orderNo);
} else {
log.error("携程分销订单退订失败,orderNo: {}, result: {}", orderNo, result);
}
} catch (Exception e) {
log.error("携程分销订单退订异常,orderNo: {}", orderNo, e);
}
}
} }
@@ -279,23 +279,6 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
return baseMapper.getOrderByNumber(orderNumber); return baseMapper.getOrderByNumber(orderNumber);
} }
@Override
public Order getOrderByNumberAndTenant(String orderNumber, String tenantId) {
return baseMapper.getOrderByNumberAndTenant(orderNumber, tenantId);
}
@Override
public Order getOrderByNumberWithFallback(String orderNumber, String tenantId) {
// 先按订单号+租户严格查询
Order order = baseMapper.getOrderByNumberAndTenant(orderNumber, tenantId);
if (order != null) {
return order;
}
// 降级:仅按订单号查询(回调场景配置租户可能与订单租户不一致)
log.info("按租户[{}]未查到订单[{}],降级按订单号查询", tenantId, orderNumber);
return baseMapper.getOrderByNumber(orderNumber);
}
@Override @Override
public boolean updateOrder(Order order) { public boolean updateOrder(Order order) {
try { try {
@@ -1,7 +1,7 @@
package com.central.order.util; package com.central.order.util;
import jakarta.servlet.ServletInputStream; import javax.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@@ -26,16 +26,4 @@ public class StringUtils {
return "0.00元"; return "0.00元";
} }
} }
/**
* 分(字符串)转元(字符串,纯数字,保留两位小数),用于支付宝 SDK total_amount/refund_amount。
*/
public static String fenToYuanAmount(String fenStr) {
if (fenStr == null || fenStr.isEmpty()) {
return "0.00";
}
long fen = Long.parseLong(fenStr.trim());
return new java.math.BigDecimal(fen).movePointLeft(2)
.setScale(2, java.math.RoundingMode.HALF_UP).toPlainString();
}
} }
@@ -1,12 +0,0 @@
-- 指点飞行安全审计字段;适用于已执行初始迁移的数据库。
ALTER TABLE mission_fly_to_point
ADD COLUMN clearance_status VARCHAR(20) NOT NULL DEFAULT 'UNVERIFIED' COMMENT '净空状态:VERIFIED / UNVERIFIED',
ADD COLUMN clearance_meters FLOAT DEFAULT NULL COMMENT '计算得到的最小净空(米)',
ADD COLUMN candidate_surface_height FLOAT DEFAULT NULL COMMENT '点击命中的模型或地形表面椭球高,仅审计使用',
ADD COLUMN risk_acknowledged TINYINT NOT NULL DEFAULT 0 COMMENT '是否已确认未验证净空风险',
ADD COLUMN risk_reason VARCHAR(512) DEFAULT NULL COMMENT '风险原因',
ADD COLUMN risk_acknowledged_user_id BIGINT DEFAULT NULL COMMENT '确认风险的账户ID',
ADD COLUMN risk_acknowledged_username VARCHAR(64) DEFAULT NULL COMMENT '确认风险的账户名';
ALTER TABLE mission_fly_to_point
ADD UNIQUE KEY uk_mission_fly_to_point_seq (mission_code, seq);
@@ -1,25 +0,0 @@
-- =====================================================
-- 指点飞行功能 - 数据库迁移脚本
-- =====================================================
-- 1. missions 表新增 phase 字段
ALTER TABLE missions ADD COLUMN phase VARCHAR(20) DEFAULT 'ACTIVE' COMMENT '会话阶段:ACTIVE / RETURNING';
-- 2. 创建 mission_fly_to_point 子表(记录每次目标更新)
CREATE TABLE IF NOT EXISTS mission_fly_to_point (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键',
mission_code VARCHAR(64) NOT NULL COMMENT '关联任务编码',
fly_to_id VARCHAR(64) NOT NULL COMMENT '飞行会话ID(= missionCode)',
command_id VARCHAR(64) DEFAULT NULL COMMENT '设备命令ID',
seq INT DEFAULT 1 COMMENT '目标序号(1, 2, 3...)',
command_type VARCHAR(32) NOT NULL COMMENT '指令类型:fly_to_point / fly_to_point_update',
latitude DOUBLE COMMENT '目标纬度',
longitude DOUBLE COMMENT '目标经度',
height FLOAT COMMENT '目标椭球高',
max_speed FLOAT DEFAULT 12 COMMENT '最大速度',
status VARCHAR(20) DEFAULT 'SENT' COMMENT '状态:SENT / REACHED / FAILED',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
INDEX idx_mission_code (mission_code),
INDEX idx_fly_to_id (fly_to_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='指点飞行目标点记录表';
@@ -1,37 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.order.mapper.AlipayConfigMapper">
<select id="findList" resultType="com.central.alipay.entity.AlipayConfig">
SELECT * FROM alipay_config
<where>
<if test='p.type != null and p.type != ""'>
AND type = #{p.type}
</if>
<if test='p.tenantId != null and p.tenantId != ""'>
AND tenant_id = #{p.tenantId}
</if>
<if test='p.appId != null and p.appId != ""'>
AND app_id = #{p.appId}
</if>
<if test='p.status != null'>
AND status = #{p.status}
</if>
<if test='p.searchKey != null and p.searchKey != "" and p.searchValue != null and p.searchValue != ""'>
<choose>
<when test='p.searchKey == "type"'>
AND type = #{p.searchValue}
</when>
<when test='p.searchKey == "appId"'>
AND app_id LIKE CONCAT('%', #{p.searchValue}, '%')
</when>
<when test='p.searchKey == "tenantId"'>
AND tenant_id LIKE CONCAT('%', #{p.searchValue}, '%')
</when>
</choose>
</if>
</where>
ORDER BY create_time DESC
</select>
</mapper>
@@ -28,7 +28,6 @@
<result column="is_del" property="isDel"/> <result column="is_del" property="isDel"/>
<result column="create_time" property="createTime"/> <result column="create_time" property="createTime"/>
<result column="update_time" property="updateTime"/> <result column="update_time" property="updateTime"/>
<result column="phase" property="phase"/>
<!-- 临时字段 --> <!-- 临时字段 -->
<result column="tourism_name" property="tourismName"/> <result column="tourism_name" property="tourismName"/>
<result column="image_count" property="imageCount"/> <result column="image_count" property="imageCount"/>
@@ -41,7 +40,7 @@
m.workspace_id, m.tourism_id, m.mission_status, m.workspace_id, m.tourism_id, m.mission_status,
m.target_latitude, m.target_longitude, m.target_height, m.target_latitude, m.target_longitude, m.target_height,
m.start_time, m.end_time, m.creator_id, m.creator_name, m.remark, m.start_time, m.end_time, m.creator_id, m.creator_name, m.remark,
m.tenant_id, m.is_del, m.create_time, m.update_time, m.phase m.tenant_id, m.is_del, m.create_time, m.update_time
</sql> </sql>
<!-- 分页查询任务列表 --> <!-- 分页查询任务列表 -->
@@ -100,15 +99,6 @@
AND m.is_del = 0 AND m.is_del = 0
</select> </select>
<select id="getByMissionCodeForUpdate" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM missions m
WHERE m.mission_code = #{missionCode}
AND m.is_del = 0
FOR UPDATE
</select>
<!-- 更新任务状态 --> <!-- 更新任务状态 -->
<update id="updateMissionStatus"> <update id="updateMissionStatus">
UPDATE missions UPDATE missions
@@ -108,9 +108,4 @@
SELECT * FROM orders WHERE order_no = #{orderNumber} SELECT * FROM orders WHERE order_no = #{orderNumber}
</select> </select>
<!-- 根据订单编号 + 租户ID 查询订单信息(用于支付/退款回调按配置租户严格定位订单) -->
<select id="getOrderByNumberAndTenant" resultMap="OrderResultMap">
SELECT * FROM orders WHERE order_no = #{orderNumber} AND tenant_id = #{tenantId}
</select>
</mapper> </mapper>
@@ -1,6 +0,0 @@
-- 二维码表添加支付宝小程序二维码相关字段
-- 用途:在同一行 qrcodes 上挂支付宝小程序二维码图(与微信码共用 code_id 与所有业务字段)
-- 一行业务、两张图:用户扫微信码进微信小程序,扫支付宝码进支付宝小程序,后端用同一 code_id 命中同一行
ALTER TABLE qrcodes
ADD COLUMN alipay_file_id VARCHAR(64) NULL COMMENT '支付宝小程序二维码 fileId(S3)',
ADD COLUMN alipay_file_path VARCHAR(512) NULL COMMENT '支付宝小程序二维码对象 path(S3 bucket/objectKey)';
@@ -1,29 +0,0 @@
package com.central.order.mission.command;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
class FlyToPointTargetCommandTest {
@Test
void 未验证路径且未确认风险时拒绝发送() {
FlyToPointTargetCommand command = FlyToPointTargetCommand.builder()
.clearanceStatus("UNVERIFIED")
.riskAcknowledged(false)
.build();
assertThrows(IllegalArgumentException.class, command::validateRiskAcknowledgement);
}
@Test
void 已验证路径无需风险确认即可发送() {
FlyToPointTargetCommand command = FlyToPointTargetCommand.builder()
.clearanceStatus("VERIFIED")
.riskAcknowledged(false)
.build();
assertDoesNotThrow(command::validateRiskAcknowledgement);
}
}
@@ -145,53 +145,11 @@ public class SysUserController {
return appUserService.findByWxOpenid(openId,mobile,unionId); return appUserService.findByWxOpenid(openId,mobile,unionId);
} }
/**
* 根据支付宝userId查询用户信息(Feign内部调用)
* <p>
* 已有用户按 openId 匹配后更新信息返回;新用户自动注册。
*
* @param alipayUserId 支付宝 userId(alipay.system.oauth.token 返回,必填)
* @param unionId 支付宝 union_id(同 PID 下唯一,可选)
* @param mobile 手机号(自动注册时填入,可选)
* @param appId 支付宝应用ID(预留,可选)
* @return SysUser 系统用户对象(含 id/username/mobile/openId/enabled)
*/
@GetMapping(value = "/users-anon/alipayOpenId")
@Operation(summary = "根据支付宝userId查询或注册用户(Feign内部)",
description = "入参:alipayUserId(必填)+unionId+mobile+appId(可选)。"
+ "出参:SysUser 对象。逻辑:已有用户更新信息,新用户自动创建。")
@Parameter(name = "alipayUserId", description = "支付宝 userId(alipay.system.oauth.token 返回)", required = true, example = "2088xxxxxxxxxxxx")
@Parameter(name = "unionId", description = "支付宝 union_id(同 PID 下唯一)")
@Parameter(name = "mobile", description = "手机号(注册时填入)", example = "138xxxx1234")
@Parameter(name = "appId", description = "支付宝应用ID(预留)", example = "2021000000000001")
public SysUser findByAlipayOpenId(@RequestParam("alipayUserId") String alipayUserId,
@RequestParam(required = false) String unionId,
@RequestParam(required = false) String mobile,
@RequestParam(required = false) String appId) throws Exception {
return appUserService.findByAlipayOpenid(alipayUserId, unionId, mobile, appId);
}
@GetMapping("/users/{id}") @GetMapping("/users/{id}")
public SysUser findUserById(@PathVariable Long id) { public SysUser findUserById(@PathVariable Long id) {
return appUserService.getById(id); return appUserService.getById(id);
} }
/**
* 根据系统用户ID查询支付宝 openId(供 order-center 下单时获取 buyerId)
*
* @param userId 系统用户ID
* @param appId 支付宝应用ID
* @return 支付宝 userId,无映射时返回 null
*/
@GetMapping("/users/{userId}/alipay-openid")
@Operation(summary = "根据系统用户ID查询支付宝openId",
description = "查询 sys_user_third_openid 映射表,获取该用户在指定支付宝应用下的 openId")
@Parameter(name = "userId", description = "系统用户ID", required = true, example = "1001")
@Parameter(name = "appId", description = "支付宝应用ID", required = true, example = "2021000000000001")
public String getAlipayOpenIdByUserId(@PathVariable Long userId, @RequestParam String appId) {
return appUserService.getAlipayOpenIdByUserId(userId, appId);
}
/** /**
* 管理后台修改用户 * 管理后台修改用户
* *
@@ -1,15 +0,0 @@
package com.central.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.central.user.model.SysUserThirdOpenid;
import org.apache.ibatis.annotations.Mapper;
/**
* 第三方用户 OpenId 映射 Mapper
*
* @author duzhichao
* @date 2026-05-12
*/
@Mapper
public interface SysUserThirdOpenidMapper extends BaseMapper<SysUserThirdOpenid> {
}
@@ -1,43 +0,0 @@
package com.central.user.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 第三方用户 OpenId 映射表
* <p>
* 统一管理微信/支付宝等各家 openId/userId,与 SysUser.openId 解耦。
*
* @author duzhichao
* @date 2026-05-12
*/
@Data
@TableName("sys_user_third_openid")
@Schema(description = "第三方用户OpenId映射")
public class SysUserThirdOpenid {
@TableId(type = IdType.AUTO)
@Schema(description = "主键")
private Long id;
@Schema(description = "系统用户ID")
private Long userId;
@Schema(description = "第三方平台:WECHAT / ALIPAY", example = "ALIPAY")
private String provider;
@Schema(description = "第三方应用ID")
private String appId;
@Schema(description = "第三方用户唯一标识", example = "2088123456789012")
private String openId;
@Schema(description = "第三方 unionId(微信 unionId / 支付宝 union_id)")
private String unionId;
@Schema(description = "手机号")
private String mobile;
}
@@ -31,16 +31,6 @@ public interface ISysUserService extends ISuperService<SysUser> {
SysUser findByWxOpenid(String wxOpenid,String mobile,String unionId) throws Exception; SysUser findByWxOpenid(String wxOpenid,String mobile,String unionId) throws Exception;
/**
* 根据支付宝userId查询用户(关联或自动注册)
*/
SysUser findByAlipayOpenid(String alipayUserId, String unionId, String mobile, String appId) throws Exception;
/**
* 根据系统用户ID查询支付宝 openId(从 sys_user_third_openid 映射表)
*/
String getAlipayOpenIdByUserId(Long userId, String appId);
/** /**
* 通过SysUser 把roles和permissions也查询出来 * 通过SysUser 把roles和permissions也查询出来
* @param sysUser * @param sysUser
@@ -5,9 +5,9 @@ import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.constant.CommonConstant; import com.central.common.constant.CommonConstant;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.datascope.annotation.IgnoreTenantScope; import com.central.common.datascope.annotation.IgnoreTenantScope;
import com.central.common.lock.DistributedLock; import com.central.common.lock.DistributedLock;
import com.central.common.lock.ZLock;
import com.central.common.model.PageResult; import com.central.common.model.PageResult;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.common.model.SysRole; import com.central.common.model.SysRole;
@@ -22,10 +22,8 @@ import com.central.common.context.LoginUserContextHolder;
import com.central.user.feign.OrderCenterService; import com.central.user.feign.OrderCenterService;
import com.central.user.mapper.SysRoleMenuMapper; import com.central.user.mapper.SysRoleMenuMapper;
import com.central.user.mapper.SysUserMapper; import com.central.user.mapper.SysUserMapper;
import com.central.user.mapper.SysUserThirdOpenidMapper;
import com.central.user.model.SysRoleUser; import com.central.user.model.SysRoleUser;
import com.central.user.model.SysUserExcel; import com.central.user.model.SysUserExcel;
import com.central.user.model.SysUserThirdOpenid;
import com.central.user.service.ISysRoleUserService; import com.central.user.service.ISysRoleUserService;
import com.central.user.service.ISysUserService; import com.central.user.service.ISysUserService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -60,9 +58,6 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
@Resource @Resource
private SysRoleMenuMapper roleMenuMapper; private SysRoleMenuMapper roleMenuMapper;
@Resource
private SysUserThirdOpenidMapper sysUserThirdOpenidMapper;
@Autowired @Autowired
private DistributedLock lock; private DistributedLock lock;
@@ -111,25 +106,7 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
sysUser.setMobile(mobile); sysUser.setMobile(mobile);
} }
} else { } else {
// 未找到 → 先按手机号匹配已有账号(支付宝用户改用微信登录时自动关联) // 创建新用户
sysUser = null;
if (StringUtils.isNotEmpty(mobile)) {
sysUser = this.selectByMobile(mobile);
if (ObjectUtil.isNotEmpty(sysUser)) {
log.info("微信登录按手机号关联已有用户: userId={}, mobile={}", sysUser.getId(), mobile);
// 将微信 openId 写入已有用户
sysUser.setOpenId(wxOpenid);
if (StringUtils.isNotEmpty(unionId)) {
sysUser.setUnionId(unionId);
}
if (StringUtils.isNotEmpty(mobile)) {
sysUser.setMobile(mobile);
}
}
}
if (sysUser == null) {
// 全新用户
sysUser = new SysUser(); sysUser = new SysUser();
sysUser.setOpenId(wxOpenid); sysUser.setOpenId(wxOpenid);
sysUser.setUsername(wxOpenid); sysUser.setUsername(wxOpenid);
@@ -139,7 +116,6 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
sysUser.setMobile(mobile); sysUser.setMobile(mobile);
sysUser.setUnionId(unionId); sysUser.setUnionId(unionId);
} }
}
String username = sysUser.getUsername(); String username = sysUser.getUsername();
boolean result = super.saveOrUpdateIdempotency(sysUser, lock, boolean result = super.saveOrUpdateIdempotency(sysUser, lock,
@@ -150,118 +126,6 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
return result ? sysUser : new SysUser(); return result ? sysUser : new SysUser();
} }
@Override
public SysUser findByAlipayOpenid(String alipayUserId, String unionId, String mobile, String appId) throws Exception {
log.info("支付宝登录: alipayUserId={}, unionId={}, mobile={}, appId={}", alipayUserId, unionId, mobile, appId);
// 1. 查 sys_user_third_openid 映射表(不走 SysUser.openId,避免与 grantType=openId 冲突)
QueryWrapper<SysUserThirdOpenid> mappingQuery = new QueryWrapper<SysUserThirdOpenid>()
.eq("provider", "ALIPAY")
.eq("app_id", appId)
.eq("open_id", alipayUserId);
SysUserThirdOpenid mapping = sysUserThirdOpenidMapper.selectOne(mappingQuery);
SysUser sysUser = null;
if (mapping != null) {
// 已有映射 → 查到对应的 SysUser
sysUser = baseMapper.selectById(mapping.getUserId());
if (sysUser == null) {
log.error("sys_user_third_openid 映射存在但 SysUser 不存在: userId={}", mapping.getUserId());
throw new RuntimeException("用户数据异常");
}
// 更新映射信息
if (StringUtils.isNotEmpty(mobile)) {
sysUser.setMobile(mobile);
mapping.setMobile(mobile);
}
if (StringUtils.isNotEmpty(unionId)) {
mapping.setUnionId(unionId);
}
sysUserThirdOpenidMapper.updateById(mapping);
log.info("支付宝用户已存在: userId={}, alipayUserId={}", sysUser.getId(), alipayUserId);
} else {
// 无映射 → 先按手机号匹配已有账号(分布式锁防并发重复创建)
String lockKey = "alipay:user:" + alipayUserId;
ZLock zLock = null;
try {
zLock = lock.tryLock(lockKey, 5, java.util.concurrent.TimeUnit.SECONDS);
if (zLock == null) {
log.warn("获取分布式锁失败,可能并发登录: {}", alipayUserId);
throw new RuntimeException("系统繁忙,请稍后重试");
}
// 双重检查:获取锁后再查一次映射表
SysUserThirdOpenid recheck = sysUserThirdOpenidMapper.selectOne(mappingQuery);
if (recheck != null) {
sysUser = baseMapper.selectById(recheck.getUserId());
} else if (StringUtils.isNotEmpty(mobile)) {
sysUser = selectByMobile(mobile);
if (ObjectUtil.isNotEmpty(sysUser)) {
log.info("按手机号关联已有用户: userId={}, mobile={}", sysUser.getId(), mobile);
sysUser.setMobile(mobile);
super.saveOrUpdateIdempotency(sysUser, lock,
LOCK_KEY_USERNAME + sysUser.getUsername(),
new QueryWrapper<SysUser>().eq("username", sysUser.getUsername()),
sysUser.getUsername() + "已存在");
insertThirdOpenidMapping(sysUser.getId(), "ALIPAY", appId, alipayUserId, unionId, mobile);
}
}
if (sysUser == null) {
sysUser = new SysUser();
sysUser.setUsername("alipay_" + alipayUserId);
sysUser.setType(UserType.APP.name());
sysUser.setPassword(alipayUserId);
sysUser.setEnabled(Boolean.TRUE);
sysUser.setMobile(mobile);
boolean saved = super.saveOrUpdateIdempotency(sysUser, lock,
LOCK_KEY_USERNAME + sysUser.getUsername(),
new QueryWrapper<SysUser>().eq("username", sysUser.getUsername()),
sysUser.getUsername() + "已存在");
if (!saved) { return new SysUser(); }
log.info("创建支付宝新用户: userId={}, alipayUserId={}", sysUser.getId(), alipayUserId);
insertThirdOpenidMapping(sysUser.getId(), "ALIPAY", appId, alipayUserId, unionId, mobile);
}
} catch (Exception e) {
log.error("支付宝用户关联加锁异常", e);
throw new RuntimeException("登录失败: " + e.getMessage(), e);
} finally {
if (zLock != null) {
try { lock.unlock(zLock); } catch (Exception ignored) {}
}
}
}
return sysUser;
}
@Override
public String getAlipayOpenIdByUserId(Long userId, String appId) {
QueryWrapper<SysUserThirdOpenid> query = new QueryWrapper<SysUserThirdOpenid>()
.eq("user_id", userId)
.eq("provider", "ALIPAY")
.eq("app_id", appId);
SysUserThirdOpenid mapping = sysUserThirdOpenidMapper.selectOne(query);
return mapping != null ? mapping.getOpenId() : null;
}
/**
* 插入 sys_user_third_openid 映射记录(依赖 DB 唯一索引 uk_provider_appid_openid 保证幂等)
*/
private void insertThirdOpenidMapping(Long userId, String provider, String appId,
String openId, String unionId, String mobile) {
try {
SysUserThirdOpenid mapping = new SysUserThirdOpenid();
mapping.setUserId(userId);
mapping.setProvider(provider);
mapping.setAppId(appId);
mapping.setOpenId(openId);
mapping.setUnionId(unionId);
mapping.setMobile(mobile);
sysUserThirdOpenidMapper.insert(mapping);
} catch (org.springframework.dao.DuplicateKeyException e) {
log.info("sys_user_third_openid 映射已存在, userId={}, provider={}, openId={}", userId, provider, openId);
}
}
@Override @Override
public void setUserPermission(SysUser sysUser) { public void setUserPermission(SysUser sysUser) {
if (sysUser != null) { if (sysUser != null) {
-2
View File
@@ -25,7 +25,5 @@
<module>zlt-zookeeper-spring-boot-starter</module> <module>zlt-zookeeper-spring-boot-starter</module>
<module>zlt-wechat-common-core</module> <module>zlt-wechat-common-core</module>
<module>zlt-wechat-spring-boot-starter</module> <module>zlt-wechat-spring-boot-starter</module>
<module>zlt-alipay-common-core</module>
<module>zlt-alipay-spring-boot-starter</module>
</modules> </modules>
</project> </project>
@@ -1,39 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.zlt</groupId>
<artifactId>zlt-commons</artifactId>
<version>6.0.0</version>
</parent>
<artifactId>zlt-alipay-common-core</artifactId>
<description>支付宝核心功能模块(实体、Feign接口、配置属性)</description>
<dependencies>
<!-- 基础依赖 -->
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-common-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.zlt</groupId>
<artifactId>zlt-db-spring-boot-starter</artifactId>
</dependency>
<!-- Knife4j (Swagger annotations) -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
</dependency>
</dependencies>
</project>
@@ -1,55 +0,0 @@
package com.central.alipay.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* 支付宝全局配置属性(仅承载全局默认值,运行时配置走 alipay_config 表)
*
* @author duzhichao
* @date 2026-05-12
*/
@Data
@ConfigurationProperties(prefix = "zlt.alipay")
public class AlipayProperties {
/**
* 是否启用支付宝模块
*/
private boolean enabled = true;
/**
* 网关地址
*/
private String gatewayUrl = "https://openapi.alipay.com/gateway.do";
/**
* 签名算法
*/
private String signType = "RSA2";
/**
* 字符集
*/
private String charset = "UTF-8";
/**
* 格式
*/
private String format = "json";
/**
* AlipayClient 缓存过期时间(秒)
*/
private int cacheExpireSeconds = 600;
/**
* 支付异步通知地址(全局默认,可被 DB 覆盖)
*/
private String notifyUrl;
/**
* 退款异步通知地址(全局默认,可被 DB 覆盖)
*/
private String refundNotifyUrl;
}
@@ -1,92 +0,0 @@
package com.central.alipay.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 支付宝配置实体(对标 WechatConfig)
*
* @author duzhichao
* @date 2026-05-12
*/
@Data
@TableName("alipay_config")
@Schema(description = "支付宝配置")
public class AlipayConfig {
@TableId(type = IdType.AUTO)
@Schema(description = "主键ID", example = "1")
private Long id;
@Schema(description = "租户ID", example = "tenant-001")
private String tenantId;
@Schema(description = "配置类型:MINI=小程序登录,PAY=交易支付", example = "PAY", allowableValues = {"MINI", "PAY"})
private String type;
@Schema(description = "支付宝 AppId", example = "2021000000000001")
private String appId;
@Schema(description = "应用私钥(PKCS8,入库加密)", accessMode = Schema.AccessMode.WRITE_ONLY)
private String appPrivateKey;
@Schema(description = "支付宝公钥(用于回调验签)", accessMode = Schema.AccessMode.WRITE_ONLY)
private String alipayPublicKey;
@Schema(description = "签名算法", example = "RSA2", allowableValues = {"RSA2", "RSA"})
private String signType;
@Schema(description = "字符集", example = "UTF-8")
private String charset;
@Schema(description = "格式", example = "json")
private String format;
@Schema(description = "网关地址", example = "https://openapi.alipay.com/gateway.do")
private String gatewayUrl;
@Schema(description = "支付异步通知地址(type=PAY 时有效)", example = "https://api.example.com/alipay/pay/notify")
private String notifyUrl;
@Schema(description = "退款异步通知地址(type=PAY 时有效)", example = "https://api.example.com/alipay/refund/notify")
private String refundNotifyUrl;
@Schema(description = "是否 ISV(服务商)模式", example = "false")
private Boolean isServiceMode;
@Schema(description = "ISV 合作伙伴 PID", example = "2088xxxxxxxxxxxx")
private String pid;
@Schema(description = "ISV 代调用时使用的 app_auth_token", accessMode = Schema.AccessMode.WRITE_ONLY)
private String authToken;
@Schema(description = "商家应用 AppId(被代调用方)", example = "2021xxxxxxxxxxxx")
private String subAppId;
@Schema(description = "间连商户号 smid", example = "2088xxxxxxxxxxxx")
private String subMerchantId;
@Schema(description = "AES 接口内容加解密 Key", accessMode = Schema.AccessMode.WRITE_ONLY)
private String encryptKey;
@Schema(description = "是否公钥证书模式", example = "false")
private Boolean certMode;
@Schema(description = "应用公钥证书路径(证书模式)")
private String appCertPath;
@Schema(description = "支付宝公钥证书路径(证书模式)")
private String alipayCertPath;
@Schema(description = "支付宝根证书路径(证书模式)")
private String alipayRootCertPath;
@Schema(description = "状态:0=禁用,1=启用", example = "1", allowableValues = {"0", "1"})
private Integer status;
@Schema(description = "备注", example = "生产环境支付配置")
private String remark;
}
@@ -1,43 +0,0 @@
package com.central.alipay.feign;
import com.central.alipay.entity.AlipayConfig;
import com.central.alipay.feign.fallback.AlipayConfigServiceFallbackFactory;
import com.central.common.constant.ServiceNameConstants;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
/**
* 支付宝配置 Feign 客户端(服务端在 order-center)
*
* @author duzhichao
* @date 2026-05-12
*/
@FeignClient(name = ServiceNameConstants.ORDER_SERVICE, fallbackFactory = AlipayConfigServiceFallbackFactory.class, dismiss404 = true)
public interface AlipayConfigService {
/**
* 根据类型和租户ID查询配置
*/
@GetMapping(value = "/alipay/config/type/{type}")
AlipayConfig getConfig(@PathVariable("type") String type, @RequestParam("tenantId") String tenantId);
/**
* 根据 AppId 和类型查询配置
*/
@GetMapping(value = "/alipay/config/app/{appId}")
AlipayConfig getConfigByAppId(@PathVariable("appId") String appId, @RequestParam("type") String type);
/**
* 根据 AppId 查询配置(不区分类型,用于回调定位)
*/
@GetMapping(value = "/alipay/config/app/{appId}/any")
AlipayConfig getConfigByAppId(@PathVariable("appId") String appId);
/**
* 根据子商户号获取配置(ISV 模式专用)
*/
@GetMapping(value = "/alipay/config/sub/{subMerchantId}")
AlipayConfig getConfigBySubMerchantId(@PathVariable("subMerchantId") String subMerchantId);
}

Some files were not shown because too many files have changed in this diff Show More