fix:无人船
This commit is contained in:
@@ -85,7 +85,10 @@
|
|||||||
"Bash(do echo \"=== $file ===\")",
|
"Bash(do echo \"=== $file ===\")",
|
||||||
"Read(//f/project/go-fly-platform-services/**)",
|
"Read(//f/project/go-fly-platform-services/**)",
|
||||||
"Bash(find \"F:/project/go-fly-platform-services/zlt-web/react-web-next/src/pages/orders/VideoTemplate\" -type f \\\\\\( -name \"*.tsx\" -o -name \"*.ts\" -o -name \"*.jsx\" -o -name \"*.js\" -o -name \"*.json\" \\\\\\) 2>/dev/null | head -50)",
|
"Bash(find \"F:/project/go-fly-platform-services/zlt-web/react-web-next/src/pages/orders/VideoTemplate\" -type f \\\\\\( -name \"*.tsx\" -o -name \"*.ts\" -o -name \"*.jsx\" -o -name \"*.js\" -o -name \"*.json\" \\\\\\) 2>/dev/null | head -50)",
|
||||||
"Bash(find \"F:/project/go-fly-platform-services/zlt-web/react-web-next/src/services\" -type f \\\\\\( -name \"*.ts\" -o -name \"*.tsx\" \\\\\\) 2>/dev/null | grep -i order)"
|
"Bash(find \"F:/project/go-fly-platform-services/zlt-web/react-web-next/src/services\" -type f \\\\\\( -name \"*.ts\" -o -name \"*.tsx\" \\\\\\) 2>/dev/null | grep -i order)",
|
||||||
|
"Bash(ls /f/project/go-fly-platform-services/zlt-business/device-center/src/main/java/com/central/device/controller/*.java)",
|
||||||
|
"Bash(ls /f/project/go-fly-platform-services/zlt-business/device-center/src/main/java/com/central/device/service/*.java)",
|
||||||
|
"Bash(ls /f/project/go-fly-platform-services/zlt-business/device-center/src/main/java/com/central/device/entity/*.java)"
|
||||||
],
|
],
|
||||||
"deny": [],
|
"deny": [],
|
||||||
"ask": []
|
"ask": []
|
||||||
|
|||||||
@@ -0,0 +1,832 @@
|
|||||||
|
# go-fly-platform-services 项目 Skill
|
||||||
|
|
||||||
|
**⚠️ 强制规范:所有后台开发必须严格遵循本 Skill 文档中的所有规范、模式和最佳实践**
|
||||||
|
|
||||||
|
## 项目概览
|
||||||
|
|
||||||
|
**项目名称**: go-fly-platform-services (中央平台微服务)
|
||||||
|
**技术栈**: Spring Boot 3.1 + Spring Cloud 2022 + MyBatis-Plus 3.x
|
||||||
|
**Java 版本**: 17
|
||||||
|
**构建工具**: Maven 3.8+
|
||||||
|
**架构模式**: 微服务 + 多租户 + OAuth2 认证
|
||||||
|
|
||||||
|
### 核心特性
|
||||||
|
- 多租户架构(租户级数据隔离 + 数据权限控制)
|
||||||
|
- OAuth2 认证授权(支持密码、手机号、OpenID、第三方登录)
|
||||||
|
- 分布式锁与幂等性保证
|
||||||
|
- 全链路追踪(TraceId 跨服务传播)
|
||||||
|
- 动态路由(Nacos 配置中心热更新)
|
||||||
|
- 服务熔断降级(Sentinel + Feign Fallback)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### 1. 如何添加新的业务模块?
|
||||||
|
|
||||||
|
1. 在 `zlt-business/` 下创建新模块
|
||||||
|
2. 复制标准包结构(controller/service/mapper/model)
|
||||||
|
3. 实体类继承 `SuperEntity`
|
||||||
|
4. Mapper 继承 `SuperMapper<T>`
|
||||||
|
5. Service 接口继承 `ISuperService<T>`
|
||||||
|
6. Service 实现继承 `SuperServiceImpl<Mapper, Entity>`
|
||||||
|
7. 配置 `bootstrap.yml` 设置服务名
|
||||||
|
|
||||||
|
### 2. 如何实现服务间调用?
|
||||||
|
|
||||||
|
```java
|
||||||
|
// 1. 定义Feign客户端
|
||||||
|
@FeignClient(name = "user-center", fallback = UserServiceFallback.class)
|
||||||
|
public interface UserService {
|
||||||
|
@GetMapping("/users/{id}")
|
||||||
|
Result<SysUser> findById(@PathVariable Long id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 实现降级处理
|
||||||
|
@Component
|
||||||
|
public class UserServiceFallback implements UserService {
|
||||||
|
@Override
|
||||||
|
public Result<SysUser> findById(Long id) {
|
||||||
|
return Result.failed("用户服务不可用");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 使用
|
||||||
|
@Autowired
|
||||||
|
private UserService userService;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 如何处理多租户数据?
|
||||||
|
|
||||||
|
**自动隔离**: 默认所有查询自动添加租户条件
|
||||||
|
|
||||||
|
**跳过隔离**: 使用 `@IgnoreTenantScope` 注解
|
||||||
|
|
||||||
|
**配置忽略表**: 在 `application.yml` 配置 `zlt.tenant.ignoreTables`
|
||||||
|
|
||||||
|
### 4. 如何实现分布式锁?
|
||||||
|
|
||||||
|
```java
|
||||||
|
// 注解方式(推荐)
|
||||||
|
@Lock(key = "order:create", waitTime = 5, leaseTime = 10)
|
||||||
|
public void createOrder() { ... }
|
||||||
|
|
||||||
|
// 手动方式
|
||||||
|
ZLock lock = distributedLock.tryLock("key", 5, 10, TimeUnit.SECONDS);
|
||||||
|
try {
|
||||||
|
// 业务逻辑
|
||||||
|
} finally {
|
||||||
|
distributedLock.unlock(lock);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 如何配置动态路由?
|
||||||
|
|
||||||
|
在 Nacos 配置中心创建配置:
|
||||||
|
- Data ID: `scg-routes`
|
||||||
|
- Group: `SCG_GATEWAY`
|
||||||
|
- 格式: JSON 数组的 RouteDefinition
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 快速参考
|
||||||
|
|
||||||
|
### 端口分配
|
||||||
|
- 认证中心: 8000
|
||||||
|
- 网关: 9900
|
||||||
|
- 用户中心: 7000
|
||||||
|
- 文件中心: 5000
|
||||||
|
- 日志中心: 7200
|
||||||
|
- 应用监控: 6500
|
||||||
|
- Nacos: 8848
|
||||||
|
|
||||||
|
### 关键配置项
|
||||||
|
```yaml
|
||||||
|
# 多租户
|
||||||
|
zlt.tenant.enable: true
|
||||||
|
|
||||||
|
# URL权限
|
||||||
|
zlt.security.auth.urlPermission.enable: false
|
||||||
|
|
||||||
|
# 动态路由
|
||||||
|
zlt.gateway.dynamicRoute.enabled: true
|
||||||
|
|
||||||
|
# 单点登录
|
||||||
|
zlt.security.auth.isSingleLogin: true
|
||||||
|
```
|
||||||
|
|
||||||
|
### 核心依赖版本
|
||||||
|
- Spring Boot: 3.1.6
|
||||||
|
- Spring Cloud: 2022.0.4
|
||||||
|
- Spring Cloud Alibaba: 2022.0.0.0
|
||||||
|
- MyBatis-Plus: 3.5.4.1
|
||||||
|
- Java: 17
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 项目文档位置
|
||||||
|
|
||||||
|
- **仓库指南**: `AGENTS.md`
|
||||||
|
- **项目文档**: `zlt-doc/`
|
||||||
|
- **API文档**: 启动服务后访问 `/doc.html`
|
||||||
|
- **README**: `README.md`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Git 操作限制
|
||||||
|
|
||||||
|
**重要**: 除非用户明确要求,否则不要执行任何 Git 操作:
|
||||||
|
- 禁止自动 commit、push、pull、merge、rebase
|
||||||
|
- 需要读取 Git 元数据时先获得用户确认
|
||||||
|
- 破坏性操作(reset、force push)必须明确风险并征得同意
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Agent 使用建议
|
||||||
|
|
||||||
|
### 适合场景
|
||||||
|
- 生成标准 CRUD 代码
|
||||||
|
- 添加新的业务模块
|
||||||
|
- 实现服务间调用
|
||||||
|
- 配置多租户隔离
|
||||||
|
- 添加缓存和分布式锁
|
||||||
|
- 生成 API 文档
|
||||||
|
|
||||||
|
### 注意事项
|
||||||
|
- 遵循现有代码风格和命名规范
|
||||||
|
- 使用项目提供的基类和工具类
|
||||||
|
- 添加适当的注释和文档
|
||||||
|
- 考虑多租户和权限控制
|
||||||
|
- 添加审计日志和链路追踪
|
||||||
|
- 实现服务降级和熔断
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*最后更新: 2026-04-01*
|
||||||
|
|
||||||
|
### 测试框架
|
||||||
|
- JUnit 4 / JUnit 5(按模块)
|
||||||
|
- 测试类命名: `*Test.java`
|
||||||
|
- 测试类位置: `src/test/java`
|
||||||
|
|
||||||
|
### 测试要求
|
||||||
|
- 为新增逻辑补充单测
|
||||||
|
- 测试用例相互独立、可重复
|
||||||
|
- 提PR前执行: `mvn -pl <module> -am test`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 提交规范
|
||||||
|
|
||||||
|
### 约定式提交
|
||||||
|
格式: `type(scope): 简要说明`
|
||||||
|
|
||||||
|
**类型**:
|
||||||
|
- `feat` - 新功能
|
||||||
|
- `fix` - 修复bug
|
||||||
|
- `docs` - 文档
|
||||||
|
- `refactor` - 重构
|
||||||
|
- `test` - 测试
|
||||||
|
- `chore` - 构建/工具
|
||||||
|
|
||||||
|
**示例**:
|
||||||
|
```
|
||||||
|
feat(订单中心): 添加订单导出功能
|
||||||
|
fix(用户中心): 修复用户登录验证码失效问题
|
||||||
|
docs(README): 更新部署文档
|
||||||
|
```
|
||||||
|
|
||||||
|
### PR规范
|
||||||
|
- 描述清晰:目的/影响/涉及模块
|
||||||
|
- 包含测试说明
|
||||||
|
- 前端改动附截图
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
### Lombok
|
||||||
|
```java
|
||||||
|
@Slf4j // 自动注入logger
|
||||||
|
@Data // getter/setter/toString
|
||||||
|
@EqualsAndHashCode // equals/hashCode
|
||||||
|
@AllArgsConstructor // 全参构造
|
||||||
|
@NoArgsConstructor // 无参构造
|
||||||
|
```
|
||||||
|
|
||||||
|
### MyBatis-Plus
|
||||||
|
```java
|
||||||
|
@TableName("table_name") // 表名映射
|
||||||
|
@TableId // 主键
|
||||||
|
@TableField(exist = false) // 非数据库字段
|
||||||
|
@TableField(fill = FieldFill.INSERT) // 插入时填充
|
||||||
|
@TableLogic // 逻辑删除
|
||||||
|
```
|
||||||
|
|
||||||
|
### Spring
|
||||||
|
```java
|
||||||
|
@RestController // REST控制器
|
||||||
|
@Service // 业务层
|
||||||
|
@Transactional // 事务管理
|
||||||
|
@Cacheable // 查询缓存
|
||||||
|
@CachePut // 更新缓存
|
||||||
|
@CacheEvict // 清除缓存
|
||||||
|
@Async // 异步执行
|
||||||
|
```
|
||||||
|
|
||||||
|
### 项目自定义
|
||||||
|
```java
|
||||||
|
@AuditLog(operation = "操作描述") // 审计日志
|
||||||
|
@IgnoreTenantScope // 跳过租户隔离
|
||||||
|
@Lock(key = "lock_key") // 分布式锁
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 开发最佳实践
|
||||||
|
|
||||||
|
**⚠️ 重要:所有后台开发必须严格遵循本 Skill 中的规范和模式**
|
||||||
|
|
||||||
|
### 1. 实体类设计
|
||||||
|
- 继承 `SuperEntity` 获得id/createTime/updateTime
|
||||||
|
- **必须为每个字段添加注释**,说明字段的业务含义
|
||||||
|
- 枚举类型注明可选值,布尔类型注明 true/false 含义
|
||||||
|
- 使用 `@TableLogic` 实现逻辑删除
|
||||||
|
- 非数据库字段标记 `@TableField(exist = false)`
|
||||||
|
|
||||||
|
### 2. Service层规范
|
||||||
|
- 接口继承 `ISuperService<T>`
|
||||||
|
- 实现继承 `SuperServiceImpl<Mapper, Entity>`
|
||||||
|
- **优先使用 MPJBaseMapper 的 Lambda 方式**,少用 XML
|
||||||
|
- 只有复杂 SQL(多表关联、子查询、复杂统计)才使用 XML
|
||||||
|
- 事务方法添加 `@Transactional(rollbackFor = Exception.class)`
|
||||||
|
- 并发操作使用 `saveOrUpdateIdempotency()` 保证幂等性
|
||||||
|
|
||||||
|
### 3. 用户查询规范
|
||||||
|
- **全局统一使用**: `SysUser sysUser = userService.findUserById(userId);`
|
||||||
|
- 获取当前登录用户: `LoginUserContextHolder.getUser()`
|
||||||
|
|
||||||
|
### 4. 缓存使用
|
||||||
|
- 查询使用 `@Cacheable`
|
||||||
|
- 更新使用 `@CachePut`
|
||||||
|
- 删除使用 `@CacheEvict`
|
||||||
|
- 配置缓存过期时间
|
||||||
|
|
||||||
|
### 4. 异常处理
|
||||||
|
- 业务异常抛出 `BusinessException`
|
||||||
|
- 全局异常由 `DefaultExceptionAdvice` 统一处理
|
||||||
|
- 返回统一格式 `Result<T>`
|
||||||
|
|
||||||
|
### 5. 日志规范
|
||||||
|
- 使用 `@Slf4j` 注解
|
||||||
|
- 关键操作添加 `@AuditLog`
|
||||||
|
- 日志自动包含 TraceId
|
||||||
|
|
||||||
|
### 6. 安全规范
|
||||||
|
- 禁止提交密钥和凭据
|
||||||
|
- 使用环境变量或配置中心
|
||||||
|
- 敏感操作添加审计日志
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
### OAuth2 认证中心(zlt-uaa)
|
||||||
|
|
||||||
|
**支持的授权方式**:
|
||||||
|
- `password` - 用户名密码
|
||||||
|
- `password_code` - 密码+验证码
|
||||||
|
- `mobile` - 手机号认证
|
||||||
|
- `openid` - OpenID认证
|
||||||
|
- `tencent` - 腾讯第三方登录
|
||||||
|
|
||||||
|
**Token生成流程**:
|
||||||
|
```
|
||||||
|
登录请求 → AuthenticationProvider → BaseAuthenticationProvider
|
||||||
|
→ TokenGenerator (JWT + AccessToken + RefreshToken)
|
||||||
|
→ 保存到Redis → 返回Token响应
|
||||||
|
```
|
||||||
|
|
||||||
|
**Token增强**: 自动添加用户ID、用户名、账户类型等信息
|
||||||
|
|
||||||
|
**Token存储**: Redis(默认)或内存
|
||||||
|
|
||||||
|
### API网关(sc-gateway)
|
||||||
|
|
||||||
|
**动态路由**: Nacos配置中心热更新
|
||||||
|
```yaml
|
||||||
|
zlt:
|
||||||
|
gateway:
|
||||||
|
dynamicRoute:
|
||||||
|
enabled: true
|
||||||
|
dataType: nacos
|
||||||
|
```
|
||||||
|
|
||||||
|
**过滤器链**:
|
||||||
|
```
|
||||||
|
请求 → TraceFilter(链路追踪) → RequestFilter(方法验证)
|
||||||
|
→ ResourceServer(Token验证) → PermissionAuthManager(权限检查)
|
||||||
|
→ 后端服务
|
||||||
|
```
|
||||||
|
|
||||||
|
**权限检查**:
|
||||||
|
- 超级管理员(admin)自动放行
|
||||||
|
- 应用黑白名单控制
|
||||||
|
- URL级别权限验证
|
||||||
|
- 支持忽略列表配置
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 构建与运行
|
||||||
|
|
||||||
|
### 构建命令
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 全量构建(跳过测试)
|
||||||
|
mvn -q -DskipTests clean package
|
||||||
|
|
||||||
|
# 全量测试
|
||||||
|
mvn -q test
|
||||||
|
|
||||||
|
# 指定模块构建+测试
|
||||||
|
mvn -pl zlt-business/user-center -am clean verify
|
||||||
|
```
|
||||||
|
|
||||||
|
### 本地运行
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 运行网关
|
||||||
|
mvn -pl zlt-gateway/sc-gateway -am spring-boot:run
|
||||||
|
|
||||||
|
# 运行认证中心
|
||||||
|
mvn -pl zlt-uaa -am spring-boot:run
|
||||||
|
|
||||||
|
# 从JAR运行
|
||||||
|
java -jar zlt-gateway/sc-gateway/target/*.jar
|
||||||
|
```
|
||||||
|
|
||||||
|
**先决条件**: JDK 17、Maven 3.8+
|
||||||
|
|
||||||
|
### 配置文件
|
||||||
|
|
||||||
|
**bootstrap.yml** (服务启动配置):
|
||||||
|
```yaml
|
||||||
|
spring:
|
||||||
|
application:
|
||||||
|
name: user-center # 服务名
|
||||||
|
```
|
||||||
|
|
||||||
|
**application.yml** (通常从Nacos读取):
|
||||||
|
```yaml
|
||||||
|
spring:
|
||||||
|
datasource:
|
||||||
|
url: jdbc:mysql://localhost/user-center
|
||||||
|
username: root
|
||||||
|
password: password
|
||||||
|
|
||||||
|
mybatis-plus:
|
||||||
|
mapper-locations: classpath:/mapper/*Mapper.xml
|
||||||
|
|
||||||
|
zlt:
|
||||||
|
tenant:
|
||||||
|
enable: true
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
### 核心基础库(zlt-common-core)
|
||||||
|
|
||||||
|
**通用返回模型**:
|
||||||
|
```java
|
||||||
|
Result<T> // API返回包装 {data, resp_code, resp_msg}
|
||||||
|
PageResult<T> // 分页返回 {count, data, resp_code}
|
||||||
|
```
|
||||||
|
|
||||||
|
**用户与租户上下文**:
|
||||||
|
```java
|
||||||
|
LoginUserContextHolder.getUser() // 获取当前登录用户
|
||||||
|
TenantContextHolder.getTenantId() // 获取当前租户ID
|
||||||
|
LoginUserUtils.getCurrentUser(true) // 从请求获取用户
|
||||||
|
|
||||||
|
// 全局根据userId获取用户的标准方法
|
||||||
|
SysUser sysUser = userService.findUserById(userId);
|
||||||
|
```
|
||||||
|
|
||||||
|
**常用工具类**:
|
||||||
|
- `JsonUtil` - JSON序列化
|
||||||
|
- `IdGenerator` - 分布式ID生成
|
||||||
|
- `ExcelUtil` - Excel导入导出
|
||||||
|
- `ResponseUtil` - HTTP响应工具
|
||||||
|
|
||||||
|
**异常处理**:
|
||||||
|
- `BusinessException` - 业务异常
|
||||||
|
- `DefaultExceptionAdvice` - 全局异常处理
|
||||||
|
|
||||||
|
### 分布式锁(zlt-redis-spring-boot-starter)
|
||||||
|
|
||||||
|
```java
|
||||||
|
// 方式1: 注解驱动
|
||||||
|
@Lock(key = "order:create", waitTime = 5, leaseTime = 10)
|
||||||
|
public void createOrder() { ... }
|
||||||
|
|
||||||
|
// 方式2: 手动调用
|
||||||
|
@Autowired
|
||||||
|
private DistributedLock lock;
|
||||||
|
|
||||||
|
ZLock zlock = lock.tryLock("order:123", 5, 10, TimeUnit.SECONDS);
|
||||||
|
try {
|
||||||
|
// 业务逻辑
|
||||||
|
} finally {
|
||||||
|
lock.unlock(zlock);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Redis 缓存
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Autowired
|
||||||
|
private RedisRepository redisRepository;
|
||||||
|
|
||||||
|
// 基础操作
|
||||||
|
redisRepository.set("key", value, 3600, TimeUnit.SECONDS);
|
||||||
|
Object value = redisRepository.get("key");
|
||||||
|
redisRepository.del("key");
|
||||||
|
|
||||||
|
// Hash操作
|
||||||
|
redisRepository.hSet("hash:key", "field", value);
|
||||||
|
Object field = redisRepository.hGet("hash:key", "field");
|
||||||
|
```
|
||||||
|
|
||||||
|
### 审计日志
|
||||||
|
|
||||||
|
```java
|
||||||
|
@AuditLog(operation = "'创建订单:' + #order.orderNo")
|
||||||
|
public void createOrder(Order order) {
|
||||||
|
// 自动记录: 操作时间、操作人、操作内容、IP地址
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 多租户隔离
|
||||||
|
|
||||||
|
**自动隔离**: SQL自动添加 `WHERE tenant_id = ?`
|
||||||
|
|
||||||
|
**跳过隔离**:
|
||||||
|
```java
|
||||||
|
@IgnoreTenantScope
|
||||||
|
public List<SysUser> findAllUsers() {
|
||||||
|
// 查询所有租户的用户
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**配置忽略表**:
|
||||||
|
```yaml
|
||||||
|
zlt:
|
||||||
|
tenant:
|
||||||
|
enable: true
|
||||||
|
ignoreTables:
|
||||||
|
- sys_user
|
||||||
|
- sys_role
|
||||||
|
```
|
||||||
|
|
||||||
|
### 链路追踪
|
||||||
|
|
||||||
|
**自动传播**: TraceId 自动跨服务传递(Web → Feign → Dubbo)
|
||||||
|
|
||||||
|
**MDC集成**: 日志自动包含 TraceId
|
||||||
|
```
|
||||||
|
[TraceId: abc123] 用户登录成功
|
||||||
|
```
|
||||||
|
|
||||||
|
### 对象存储(zlt-oss-spring-boot-starter)
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Autowired
|
||||||
|
private IOssService ossService;
|
||||||
|
|
||||||
|
// 上传文件
|
||||||
|
ObjectInfo info = ossService.upload(multipartFile);
|
||||||
|
|
||||||
|
// 上传流
|
||||||
|
ObjectInfo info = ossService.upload("path/file.jpg", inputStream);
|
||||||
|
|
||||||
|
// 删除
|
||||||
|
ossService.delete("path/file.jpg");
|
||||||
|
```
|
||||||
|
|
||||||
|
支持: FastDFS、Amazon S3、阿里云OSS、腾讯云COS
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
### Controller 层
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Slf4j
|
||||||
|
@RestController
|
||||||
|
@Tag(name = "用户管理")
|
||||||
|
public class SysUserController {
|
||||||
|
@Autowired
|
||||||
|
private ISysUserService userService;
|
||||||
|
|
||||||
|
// 查询单条
|
||||||
|
@GetMapping("/users/{id}")
|
||||||
|
@Operation(summary = "根据ID查询用户")
|
||||||
|
public Result<SysUser> findById(@PathVariable Long id) {
|
||||||
|
return Result.succeed(userService.getById(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分页查询
|
||||||
|
@GetMapping("/users")
|
||||||
|
public PageResult<SysUser> findUsers(@RequestParam Map<String, Object> params) {
|
||||||
|
return userService.findUsers(params);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 新增或更新
|
||||||
|
@PostMapping("/users/saveOrUpdate")
|
||||||
|
@AuditLog(operation = "'保存用户:' + #user.username")
|
||||||
|
public Result saveOrUpdate(@RequestBody SysUser user) {
|
||||||
|
return userService.saveOrUpdateUser(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 删除
|
||||||
|
@DeleteMapping("/users/{id}")
|
||||||
|
public Result delete(@PathVariable Long id) {
|
||||||
|
userService.delUser(id);
|
||||||
|
return Result.succeed("删除成功");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**关键注解**:
|
||||||
|
- `@RestController` - REST控制器
|
||||||
|
- `@Tag` / `@Operation` - Swagger 3.0文档
|
||||||
|
- `@AuditLog` - 审计日志(自动记录操作)
|
||||||
|
- `@CachePut` / `@Cacheable` - 缓存管理
|
||||||
|
|
||||||
|
### Service 层
|
||||||
|
|
||||||
|
```java
|
||||||
|
// 接口
|
||||||
|
public interface ISysUserService extends ISuperService<SysUser> {
|
||||||
|
PageResult<SysUser> findUsers(Map<String, Object> params);
|
||||||
|
Result saveOrUpdateUser(SysUser user);
|
||||||
|
boolean delUser(Long id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 实现
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
||||||
|
implements ISysUserService {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private DistributedLock lock;
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
@Override
|
||||||
|
public Result saveOrUpdateUser(SysUser user) {
|
||||||
|
// 幂等性保证
|
||||||
|
boolean result = super.saveOrUpdateIdempotency(user, lock,
|
||||||
|
"username:" + user.getUsername(),
|
||||||
|
new QueryWrapper<SysUser>().eq("username", user.getUsername()),
|
||||||
|
"用户名已存在"
|
||||||
|
);
|
||||||
|
return result ? Result.succeed(user) : Result.failed("操作失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@IgnoreTenantScope // 跳过租户隔离
|
||||||
|
public List<SysRole> findRoles(Long userId) {
|
||||||
|
return roleMapper.findByUserId(userId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**关键点**:
|
||||||
|
- 继承 `SuperServiceImpl<Mapper, Entity>`
|
||||||
|
- `@Transactional` 事务管理
|
||||||
|
- `saveOrUpdateIdempotency()` 幂等性操作
|
||||||
|
- `@IgnoreTenantScope` 跳过多租户隔离
|
||||||
|
|
||||||
|
### Mapper 层
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Mapper
|
||||||
|
public interface SysUserMapper extends SuperMapper<SysUser> {
|
||||||
|
// 简单查询优先使用 MPJBaseMapper 的 Lambda 方式
|
||||||
|
// 复杂查询才使用 XML
|
||||||
|
List<SysUser> findList(Page<SysUser> page, @Param("u") Map<String, Object> params);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**重要规范**:
|
||||||
|
- 继承 `SuperMapper<T>` (基于 MPJBaseMapper)
|
||||||
|
- **优先使用 MPJBaseMapper 的 Lambda 方式**,少用 XML
|
||||||
|
- 只有复杂 SQL(多表关联、子查询、复杂统计)才使用 `*Mapper.xml`
|
||||||
|
|
||||||
|
**MPJBaseMapper 使用示例**:
|
||||||
|
```java
|
||||||
|
// Service 实现中使用 MPJBaseMapper
|
||||||
|
@Service
|
||||||
|
public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> {
|
||||||
|
|
||||||
|
// 简单关联查询 - 使用 MPJBaseMapper
|
||||||
|
public List<Order> findOrdersWithUser(Long userId) {
|
||||||
|
return baseMapper.selectJoinList(Order.class,
|
||||||
|
new MPJLambdaWrapper<Order>()
|
||||||
|
.selectAll(Order.class)
|
||||||
|
.select(SysUser::getUsername, SysUser::getNickname)
|
||||||
|
.leftJoin(SysUser.class, SysUser::getId, Order::getUserId)
|
||||||
|
.eq(Order::getUserId, userId)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 复杂统计查询 - 使用 XML
|
||||||
|
public List<OrderStatVO> getOrderStats(Map<String, Object> params) {
|
||||||
|
return baseMapper.getOrderStats(params);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 实体类
|
||||||
|
|
||||||
|
**重要规范**: 所有字段必须添加注释说明字段作用
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = false)
|
||||||
|
@TableName("sys_user")
|
||||||
|
public class SysUser extends SuperEntity {
|
||||||
|
/** 用户名(登录账号) */
|
||||||
|
private String username;
|
||||||
|
|
||||||
|
/** 密码(加密存储) */
|
||||||
|
private String password;
|
||||||
|
|
||||||
|
/** 昵称(显示名称) */
|
||||||
|
private String nickname;
|
||||||
|
|
||||||
|
/** 手机号 */
|
||||||
|
private String mobile;
|
||||||
|
|
||||||
|
/** 是否启用(true=启用,false=禁用) */
|
||||||
|
private Boolean enabled;
|
||||||
|
|
||||||
|
/** 用户类型(APP=移动端用户,BACKEND=后台用户) */
|
||||||
|
private String type;
|
||||||
|
|
||||||
|
/** 逻辑删除标记(true=已删除,false=未删除) */
|
||||||
|
@TableLogic
|
||||||
|
private boolean isDel;
|
||||||
|
|
||||||
|
/** 用户角色列表(非数据库字段,用于传输) */
|
||||||
|
@TableField(exist = false)
|
||||||
|
private List<SysRole> roles;
|
||||||
|
|
||||||
|
/** 角色ID(非数据库字段,用于前端传参) */
|
||||||
|
@TableField(exist = false)
|
||||||
|
private String roleId;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**基类 SuperEntity**:
|
||||||
|
```java
|
||||||
|
public class SuperEntity {
|
||||||
|
/** 主键ID(自增) */
|
||||||
|
@TableId
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
/** 创建时间(插入时自动填充) */
|
||||||
|
@TableField(fill = FieldFill.INSERT)
|
||||||
|
private Date createTime;
|
||||||
|
|
||||||
|
/** 更新时间(插入和更新时自动填充) */
|
||||||
|
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||||
|
private Date updateTime;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**字段注释规范**:
|
||||||
|
- 必须说明字段的业务含义
|
||||||
|
- 枚举类型需注明可选值
|
||||||
|
- 布尔类型需注明 true/false 的含义
|
||||||
|
- 关联字段需注明关联的表或实体
|
||||||
|
|
||||||
|
### Feign 服务调用
|
||||||
|
|
||||||
|
```java
|
||||||
|
// 客户端定义
|
||||||
|
@FeignClient(name = "order-center", fallback = OrderServiceFallback.class)
|
||||||
|
public interface OrderCenterService {
|
||||||
|
@DeleteMapping("/orders/user/{userId}")
|
||||||
|
Result<String> deleteUserOrders(@PathVariable("userId") Long userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 熔断降级
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class OrderServiceFallback implements OrderCenterService {
|
||||||
|
@Override
|
||||||
|
public Result<String> deleteUserOrders(Long userId) {
|
||||||
|
log.error("订单中心服务不可用,用户ID: {}", userId);
|
||||||
|
return Result.failed("订单中心服务不可用");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
central-platform
|
||||||
|
├── zlt-commons/ # 公共模块(14个starter)
|
||||||
|
│ ├── zlt-common-core # 核心基础库
|
||||||
|
│ ├── zlt-db-spring-boot-starter # 数据库增强
|
||||||
|
│ ├── zlt-redis-spring-boot-starter # Redis缓存
|
||||||
|
│ ├── zlt-auth-client-spring-boot-starter # OAuth2客户端
|
||||||
|
│ ├── zlt-log-spring-boot-starter # 日志链路追踪
|
||||||
|
│ ├── zlt-oss-spring-boot-starter # 对象存储
|
||||||
|
│ └── zlt-common-spring-boot-starter # 多租户过滤器
|
||||||
|
├── zlt-uaa/ # 认证中心 [8000]
|
||||||
|
├── zlt-gateway/sc-gateway/ # API网关 [9900]
|
||||||
|
├── zlt-business/ # 业务服务
|
||||||
|
│ ├── user-center # 用户中心 [7000]
|
||||||
|
│ ├── order-center # 订单中心
|
||||||
|
│ ├── device-center # 设备中心
|
||||||
|
│ ├── file-center # 文件中心 [5000]
|
||||||
|
│ ├── msg-center # 消息中心
|
||||||
|
│ └── coupon-center # 优惠券中心
|
||||||
|
├── zlt-monitor/ # 监控
|
||||||
|
│ ├── sc-admin # 应用监控 [6500]
|
||||||
|
│ └── log-center # 日志中心 [7200]
|
||||||
|
└── zlt-web/ # 前端
|
||||||
|
├── react-web-next # React前端
|
||||||
|
└── yingyan # 鹰眼前端
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 语言与编码规范
|
||||||
|
|
||||||
|
### 交互语言
|
||||||
|
- **所有回复、解释、建议、错误信息必须使用中文(简体)**
|
||||||
|
- 代码注释、日志消息、文档内容使用中文
|
||||||
|
- 编程关键字、API标识符保持原文
|
||||||
|
- 提交信息、PR描述、Issue使用中文
|
||||||
|
- 所有文本使用 UTF-8 编码
|
||||||
|
|
||||||
|
### 命名约定
|
||||||
|
- **包名**: `com.central.*`
|
||||||
|
- **模块名**: `zlt-*` 前缀
|
||||||
|
- **类名**: PascalCase(如 `SysUserController`)
|
||||||
|
- **方法/字段**: lowerCamelCase(如 `findUserById`)
|
||||||
|
- **常量**: UPPER_SNAKE_CASE(如 `TOKEN_HEADER`)
|
||||||
|
- **接口**: `I` 前缀(如 `ISysUserService`)
|
||||||
|
- **实现类**: `Impl` 后缀(如 `SysUserServiceImpl`)
|
||||||
|
- **测试类**: `*Test.java` 后缀
|
||||||
|
|
||||||
|
### 代码风格
|
||||||
|
- 4空格缩进(Java)
|
||||||
|
- 左大括号同一行
|
||||||
|
- UTF-8 编码
|
||||||
|
- 优先使用 Lombok 注解(`@Data`, `@Slf4j`)
|
||||||
|
- 尽量不要controller层编写业务代码,在service层写业务代码
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 标准分层架构
|
||||||
|
|
||||||
|
### 四层分层模式
|
||||||
|
|
||||||
|
```
|
||||||
|
Controller 层 (HTTP入口)
|
||||||
|
↓
|
||||||
|
Service 接口 (ISxxService)
|
||||||
|
↓
|
||||||
|
Service 实现 (SxxServiceImpl)
|
||||||
|
↓
|
||||||
|
Mapper 接口 (数据库访问)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 标准包结构
|
||||||
|
|
||||||
|
```java
|
||||||
|
com.central.{module}/
|
||||||
|
├── controller/ // HTTP入口层
|
||||||
|
├── service/ // Service接口
|
||||||
|
│ └── impl/ // Service实现
|
||||||
|
├── mapper/ // MyBatis-Plus Mapper
|
||||||
|
├── model/ // 实体类
|
||||||
|
│ ├── dto/ // 数据传输对象
|
||||||
|
│ └── vo/ // 值对象
|
||||||
|
├── feign/ // Feign客户端
|
||||||
|
│ └── fallback/ // 熔断降级
|
||||||
|
├── config/ // 配置类
|
||||||
|
├── constants/ // 常量
|
||||||
|
├── enums/ // 枚举
|
||||||
|
├── event/ // 事件
|
||||||
|
├── listener/ // 监听器
|
||||||
|
└── util/ // 工具类
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
@@ -0,0 +1,466 @@
|
|||||||
|
# react-web-next 项目 Skill
|
||||||
|
|
||||||
|
**适用范围**: `zlt-web/react-web-next`
|
||||||
|
|
||||||
|
**强制要求**: 在该项目中进行开发、修复、重构、迁移时,默认以本 Skill 为第一约束;除非用户明确要求,否则不要偏离这里定义的结构、边界和实现方式。
|
||||||
|
|
||||||
|
## 1. 项目一句话定义
|
||||||
|
|
||||||
|
`react-web-next` 是旧版 `zlt-web/react-web` 的重构版管理后台:
|
||||||
|
|
||||||
|
- 保持旧功能、旧接口、旧菜单路径兼容
|
||||||
|
- 用更清晰的页面/组件/service/utils 分层重组代码
|
||||||
|
- 把“租户过滤”沉淀为横切基础设施
|
||||||
|
- 在不升级核心技术栈的前提下优化 UI 与维护性
|
||||||
|
|
||||||
|
## 2. 技术边界
|
||||||
|
|
||||||
|
### 必须遵守
|
||||||
|
|
||||||
|
- React 17
|
||||||
|
- UmiJS 3.5
|
||||||
|
- Ant Design 4
|
||||||
|
- `@ant-design/pro-components` 1.x
|
||||||
|
- `@ant-design/pro-layout` 7.x
|
||||||
|
- TypeScript 4.5,且 `strict: true`
|
||||||
|
- Less + 主题变量 + 运行时主题包装
|
||||||
|
|
||||||
|
### 不要擅自做的事
|
||||||
|
|
||||||
|
- 不要切 React 18 写法再反向污染项目
|
||||||
|
- 不要引入 Ant Design 5 的 token/ConfigProvider 主题范式替换现有体系
|
||||||
|
- 不要为了“现代化”重做路由、菜单、登录态、代理机制
|
||||||
|
- 不要把页面请求逻辑重新散落回页面组件内部
|
||||||
|
|
||||||
|
## 3. 先认清这 5 个核心事实
|
||||||
|
|
||||||
|
### 3.1 这是兼容旧后台路径的重构工程
|
||||||
|
|
||||||
|
- 大量页面仍然保留 `*.html` 路径,例如 `/system/user.html`
|
||||||
|
- 这是兼容旧菜单入口、部署方式、历史链接的刻意设计
|
||||||
|
- **不要批量改路由风格,不要把 `.html` 路径私自改没**
|
||||||
|
|
||||||
|
### 3.2 开发态和构建态的 API 路径策略不同
|
||||||
|
|
||||||
|
- 开发态:靠 `config/proxy.ts` 转发
|
||||||
|
- 构建态:靠 `process.env.API_PREFIX` 注入请求前缀
|
||||||
|
- `APP_BASE` 同时影响 `base`、`publicPath` 和最终部署目录
|
||||||
|
|
||||||
|
### 3.3 租户过滤不是页面私有逻辑,而是全局基础设施
|
||||||
|
|
||||||
|
- 首选 `src/components/TenantScopeFilter/index.tsx`
|
||||||
|
- 配套缓存与 Token 保护在 `src/utils/tenantCache.ts`
|
||||||
|
- 页面如果天然受租户影响,默认要先判断是否应接入这套能力
|
||||||
|
|
||||||
|
### 3.4 应用层已经统一接管了认证行为
|
||||||
|
|
||||||
|
- 全局入口在 `src/app.tsx`
|
||||||
|
- 会自动注入 `Authorization: Bearer <token>`
|
||||||
|
- 会统一处理 401/403 与部分业务未授权码
|
||||||
|
- 会统一清理:
|
||||||
|
- `sessionStorage.access_token`
|
||||||
|
- `sessionStorage.current_user`
|
||||||
|
- 租户缓存
|
||||||
|
|
||||||
|
### 3.5 后端返回结构需要兼容 `resp_code`
|
||||||
|
|
||||||
|
默认优先兼容:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"resp_code": 0,
|
||||||
|
"resp_msg": "success",
|
||||||
|
"data": {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
前端处理后的目标语义应尽量统一为:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
success: true,
|
||||||
|
code: 0,
|
||||||
|
msg: 'success',
|
||||||
|
data: {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**结论**: 新增 service、下载、列表查询、提交保存时,都要先考虑这层兼容,不要重新定义另一套响应契约。
|
||||||
|
|
||||||
|
## 4. 目录落位规则
|
||||||
|
|
||||||
|
```text
|
||||||
|
zlt-web/react-web-next/
|
||||||
|
├─ config/
|
||||||
|
│ ├─ config.ts
|
||||||
|
│ ├─ proxy.ts
|
||||||
|
│ └─ routes.ts
|
||||||
|
├─ src/
|
||||||
|
│ ├─ app.tsx
|
||||||
|
│ ├─ global.less
|
||||||
|
│ ├─ theme.tsx
|
||||||
|
│ ├─ layouts/
|
||||||
|
│ ├─ pages/
|
||||||
|
│ ├─ services/
|
||||||
|
│ ├─ components/
|
||||||
|
│ ├─ hooks/
|
||||||
|
│ ├─ utils/
|
||||||
|
│ ├─ theme/
|
||||||
|
│ ├─ types/
|
||||||
|
│ └─ typings.d.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
### 你改代码前先判断放哪层
|
||||||
|
|
||||||
|
- 页面编排、状态、弹窗、列表交互:`src/pages/`
|
||||||
|
- 复用 UI 或复用业务组件:`src/components/`
|
||||||
|
- API 请求与协议适配:`src/services/`
|
||||||
|
- 跨页面纯逻辑、下载、导出、安全、缓存:`src/utils/`
|
||||||
|
- 与 React 生命周期强相关、可复用的逻辑:`src/hooks/`
|
||||||
|
- 顶层壳层、菜单、头部、账户区:`src/layouts/`
|
||||||
|
|
||||||
|
### 默认禁止
|
||||||
|
|
||||||
|
- 不要把接口直接堆在页面里
|
||||||
|
- 不要把页面专属状态机塞进 `utils`
|
||||||
|
- 不要把通用组件又复制一份到页面目录
|
||||||
|
|
||||||
|
## 5. 配置层规则
|
||||||
|
|
||||||
|
### `config/config.ts`
|
||||||
|
|
||||||
|
你需要知道它控制了:
|
||||||
|
|
||||||
|
- 显式路由入口:`routes.ts`
|
||||||
|
- 开发/生产差异化 `publicPath`
|
||||||
|
- `base` 与部署子路径
|
||||||
|
- Ant Design 4 主题变量
|
||||||
|
- `dynamicImport.loading`
|
||||||
|
- `process.env.API_PREFIX`
|
||||||
|
- `process.env.APP_BASE`
|
||||||
|
- `process.env.CESIUM_BASE_URL`
|
||||||
|
|
||||||
|
### 配置层修改原则
|
||||||
|
|
||||||
|
- 影响部署路径时,同时检查 `base`、`publicPath`、构建脚本
|
||||||
|
- 影响 API 访问时,同时检查 `proxy.ts` 和 `src/app.tsx` 的 request prefix
|
||||||
|
- 影响 Cesium 资源时,不要绕开 `CESIUM_BASE_URL` 另造路径机制
|
||||||
|
|
||||||
|
### `config/proxy.ts`
|
||||||
|
|
||||||
|
已存在的代理重点:
|
||||||
|
|
||||||
|
- `/api-`
|
||||||
|
- `/goflymodel`
|
||||||
|
- `/rtc`
|
||||||
|
- `/terraform`
|
||||||
|
|
||||||
|
新增代理规则前先问自己:
|
||||||
|
|
||||||
|
- 是开发态临时代理,还是生产态正式访问路径?
|
||||||
|
- 这条规则是否应该进网关,而不是前端本地代理?
|
||||||
|
|
||||||
|
### `config/routes.ts`
|
||||||
|
|
||||||
|
主要业务域:
|
||||||
|
|
||||||
|
- `system`
|
||||||
|
- `orders`
|
||||||
|
- `device`
|
||||||
|
- `log`
|
||||||
|
- `search`
|
||||||
|
- `files`
|
||||||
|
|
||||||
|
新增页面时:
|
||||||
|
|
||||||
|
- 优先挂到已有业务域下
|
||||||
|
- 保持与旧菜单 URL 兼容
|
||||||
|
- 普通后台页面默认走 `@/layouts/BasicLayout`
|
||||||
|
|
||||||
|
## 6. 页面开发规则
|
||||||
|
|
||||||
|
### 页面职责
|
||||||
|
|
||||||
|
页面负责:
|
||||||
|
|
||||||
|
- 组织查询区、操作区、表格区、弹窗区
|
||||||
|
- 管理页面级状态
|
||||||
|
- 调用 service
|
||||||
|
- 组合通用组件
|
||||||
|
|
||||||
|
页面不负责:
|
||||||
|
|
||||||
|
- 直接写大量裸请求
|
||||||
|
- 复制通用下载/导出/加密逻辑
|
||||||
|
- 重复实现租户缓存或登录态处理
|
||||||
|
|
||||||
|
### 列表页默认长相
|
||||||
|
|
||||||
|
- 优先 ProTable / Ant Design Pro 风格
|
||||||
|
- 查询区、工具栏、表格区分层清晰
|
||||||
|
- 批量操作与单行操作分离
|
||||||
|
- 页面如果受租户影响,优先在工具栏接入 `TenantScopeFilter`
|
||||||
|
|
||||||
|
### 复杂页面建议拆法
|
||||||
|
|
||||||
|
优先拆成:
|
||||||
|
|
||||||
|
1. 页面容器
|
||||||
|
2. 表格或主展示区
|
||||||
|
3. 查询条件区
|
||||||
|
4. 编辑弹窗/抽屉
|
||||||
|
5. service
|
||||||
|
6. 页面专属 hooks 或 utils
|
||||||
|
|
||||||
|
## 7. 组件开发规则
|
||||||
|
|
||||||
|
### 统一组件规范
|
||||||
|
|
||||||
|
- 一律函数组件 + Hooks
|
||||||
|
- Props 必须显式定义 TypeScript 类型
|
||||||
|
- 优先保持低副作用、低耦合、可复用
|
||||||
|
- 页面通用视觉组件优先放到 `src/components/ui/`
|
||||||
|
|
||||||
|
### 优先复用的现成组件
|
||||||
|
|
||||||
|
- `TenantScopeFilter`
|
||||||
|
- `ActionBar`
|
||||||
|
- `GradientButton`
|
||||||
|
- `GlassCard`
|
||||||
|
- `ThemeSwitch`
|
||||||
|
- `PageHeaderPlus`
|
||||||
|
|
||||||
|
### 组件设计原则
|
||||||
|
|
||||||
|
- 复用价值高的交互下沉到组件层
|
||||||
|
- 单页面专属又很重的块,不要强行抽成“伪通用”组件
|
||||||
|
- 组件内部不要私自接管全局登录态或全局路由行为
|
||||||
|
|
||||||
|
## 8. Service 层规则
|
||||||
|
|
||||||
|
### 基本要求
|
||||||
|
|
||||||
|
- 所有请求默认进入 `src/services/`
|
||||||
|
- 一个文件对应一个业务域
|
||||||
|
- 统一使用 `request('/api-xxx/...')`
|
||||||
|
- 统一处理参数映射和返回兼容
|
||||||
|
|
||||||
|
### Service 层该做什么
|
||||||
|
|
||||||
|
- 管理接口路径
|
||||||
|
- 管理请求方法和参数
|
||||||
|
- 处理返回数据兼容
|
||||||
|
- 隔离页面与后端协议细节
|
||||||
|
|
||||||
|
### Service 层不该做什么
|
||||||
|
|
||||||
|
- 不要掺杂大量页面状态
|
||||||
|
- 不要做重 UI 的逻辑
|
||||||
|
- 不要重新实现 token 注入
|
||||||
|
|
||||||
|
### 已有参考
|
||||||
|
|
||||||
|
- `src/services/login.ts`
|
||||||
|
- `src/services/tenant.ts`
|
||||||
|
- `src/services/orders.ts`
|
||||||
|
|
||||||
|
### 写新 service 的默认模板
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { request } from 'umi';
|
||||||
|
|
||||||
|
export async function queryExample(params: Record<string, unknown>) {
|
||||||
|
return request('/api-example/path', {
|
||||||
|
method: 'GET',
|
||||||
|
params,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveExample(data: Record<string, unknown>) {
|
||||||
|
return request('/api-example/path', {
|
||||||
|
method: 'POST',
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 9. Utils 与 Hooks 规则
|
||||||
|
|
||||||
|
### `src/utils/` 已有重点能力
|
||||||
|
|
||||||
|
- `request.ts`
|
||||||
|
- `download.ts`
|
||||||
|
- `export.ts`
|
||||||
|
- `rsaUtil.ts`
|
||||||
|
- `securityUtil.ts`
|
||||||
|
- `tenantCache.ts`
|
||||||
|
|
||||||
|
### 什么时候放 utils
|
||||||
|
|
||||||
|
- 与 React 生命周期无关
|
||||||
|
- 跨页面可复用
|
||||||
|
- 纯逻辑、下载、导出、加密、缓存工具
|
||||||
|
|
||||||
|
### 什么时候放 hooks
|
||||||
|
|
||||||
|
- 跟组件生命周期、effect、状态协同强相关
|
||||||
|
- 需要被多个页面/组件复用
|
||||||
|
- 典型例子:`src/hooks/useSecurity.ts`
|
||||||
|
|
||||||
|
### 不要放错层
|
||||||
|
|
||||||
|
- 单纯对象转换,不要写成 hook
|
||||||
|
- 页面专属临时状态,不要塞进 utils
|
||||||
|
|
||||||
|
## 10. 布局与主题规则
|
||||||
|
|
||||||
|
### 布局
|
||||||
|
|
||||||
|
`src/layouts/BasicLayout.tsx` 负责:
|
||||||
|
|
||||||
|
- 主后台壳层
|
||||||
|
- 菜单和路由联动
|
||||||
|
- 面包屑
|
||||||
|
- 账户区
|
||||||
|
- 统一框架风格
|
||||||
|
|
||||||
|
规则:
|
||||||
|
|
||||||
|
- 普通后台页默认挂在 `BasicLayout` 下
|
||||||
|
- 不要为普通业务页再造一层平行顶层布局
|
||||||
|
|
||||||
|
### 主题
|
||||||
|
|
||||||
|
这个项目是双层主题体系:
|
||||||
|
|
||||||
|
1. Umi `theme` 配置 Ant Design 4 基础 token
|
||||||
|
2. `src/theme.tsx` + `src/theme/modern.less` + `src/global.less` 做增强和运行时切换
|
||||||
|
|
||||||
|
样式开发要求:
|
||||||
|
|
||||||
|
- 优先复用已有变量、阴影、渐变、间距
|
||||||
|
- 不要到处写魔法色值
|
||||||
|
- 保持现代后台而不是另起一套审美体系
|
||||||
|
|
||||||
|
## 11. 登录、安全、租户三条红线
|
||||||
|
|
||||||
|
### 登录与安全
|
||||||
|
|
||||||
|
- 登录页:`src/pages/user/Login`
|
||||||
|
- 登录 service:`src/services/login.ts`
|
||||||
|
- 前端密码加密:`jsencrypt`
|
||||||
|
- Token 存储:
|
||||||
|
- `sessionStorage.access_token`
|
||||||
|
- `sessionStorage.current_user`
|
||||||
|
|
||||||
|
禁止:
|
||||||
|
|
||||||
|
- 裸写明文密码提交流程替换现有逻辑
|
||||||
|
- 绕开全局 request 拦截器单独处理认证头
|
||||||
|
|
||||||
|
### 租户
|
||||||
|
|
||||||
|
默认判断:
|
||||||
|
|
||||||
|
- 该页面数据是否按租户隔离?
|
||||||
|
- 如果是,优先接入 `TenantScopeFilter`
|
||||||
|
|
||||||
|
禁止:
|
||||||
|
|
||||||
|
- 页面自己维护另一份租户树缓存
|
||||||
|
- 页面自己发明新的“包含子租户”参数语义
|
||||||
|
- 每个接口手写重复租户拼接逻辑而不复用现有设施
|
||||||
|
|
||||||
|
## 12. 3D / 地图相关边界
|
||||||
|
|
||||||
|
虽然它是管理后台,但已内置 3D 能力:
|
||||||
|
|
||||||
|
- 路由:
|
||||||
|
- `/device/3dModel.html`
|
||||||
|
- `/device/mapDashboard.html`
|
||||||
|
- 代理:
|
||||||
|
- `/goflymodel`
|
||||||
|
- `/rtc`
|
||||||
|
- `/terraform`
|
||||||
|
|
||||||
|
规则:
|
||||||
|
|
||||||
|
- 资源路径走 `CESIUM_BASE_URL`
|
||||||
|
- 模型/流媒体跨域优先沿用现有代理策略
|
||||||
|
- 不要随意替换资源根路径方案
|
||||||
|
|
||||||
|
## 13. TypeScript 规则
|
||||||
|
|
||||||
|
- 必须尊重 `strict: true`
|
||||||
|
- 优先写明确接口/类型
|
||||||
|
- 路径别名统一使用 `@/`
|
||||||
|
- 全局声明与补充类型优先查看:
|
||||||
|
- `src/typings.d.ts`
|
||||||
|
- `src/types/`
|
||||||
|
|
||||||
|
严格禁止:
|
||||||
|
|
||||||
|
- `as any`
|
||||||
|
- `@ts-ignore`
|
||||||
|
- `@ts-expect-error`
|
||||||
|
|
||||||
|
## 14. 典型工作流
|
||||||
|
|
||||||
|
### 新增后台页面
|
||||||
|
|
||||||
|
1. 在 `config/routes.ts` 补路由,优先挂已有业务域
|
||||||
|
2. 在 `src/pages/<domain>/` 建页面目录
|
||||||
|
3. 在 `src/services/<domain>.ts` 补接口
|
||||||
|
4. 判断是否需要接入 `TenantScopeFilter`
|
||||||
|
5. 优先复用 `src/components/ui/` 组件
|
||||||
|
6. 样式继承现有主题变量
|
||||||
|
7. 确保响应兼容 `resp_code`
|
||||||
|
|
||||||
|
### 从旧 `react-web` 迁移页面
|
||||||
|
|
||||||
|
1. 先保功能等价,不先追求重写
|
||||||
|
2. 保持接口地址、菜单 URL、参数语义尽量不变
|
||||||
|
3. 把旧页拆成:页面 / 组件 / service / utils
|
||||||
|
4. 把租户过滤从页面私有逻辑改为基础设施接入
|
||||||
|
5. 再做局部 UI 统一
|
||||||
|
|
||||||
|
## 15. 决策清单
|
||||||
|
|
||||||
|
动手前自检:
|
||||||
|
|
||||||
|
- 这次改动是否破坏旧菜单 URL 兼容?
|
||||||
|
- 这个请求是否应该放进现有 `src/services/`?
|
||||||
|
- 这个页面是否应该接入租户过滤?
|
||||||
|
- 是否复用了已有下载/导出/安全/缓存工具?
|
||||||
|
- 是否仍然处在 React 17 + Antd4 + Umi3 的边界内?
|
||||||
|
- 是否兼容 `resp_code / resp_msg / data`?
|
||||||
|
|
||||||
|
## 16. 明确禁止事项
|
||||||
|
|
||||||
|
- 擅自升级 React 18 / Ant Design 5 写法
|
||||||
|
- 在页面中大量内联请求绕开 service
|
||||||
|
- 为普通页面重复造布局壳层
|
||||||
|
- 绕开全局 request 拦截器自行接管授权
|
||||||
|
- 批量移除 `.html` 路径兼容
|
||||||
|
- 新造一套与现有主题冲突的视觉体系
|
||||||
|
|
||||||
|
## 17. 优先参考文件
|
||||||
|
|
||||||
|
- `zlt-web/react-web-next/config/config.ts`
|
||||||
|
- `zlt-web/react-web-next/config/routes.ts`
|
||||||
|
- `zlt-web/react-web-next/config/proxy.ts`
|
||||||
|
- `zlt-web/react-web-next/src/app.tsx`
|
||||||
|
- `zlt-web/react-web-next/src/layouts/BasicLayout.tsx`
|
||||||
|
- `zlt-web/react-web-next/src/components/TenantScopeFilter/index.tsx`
|
||||||
|
- `zlt-web/react-web-next/src/services/login.ts`
|
||||||
|
- `zlt-web/react-web-next/src/services/tenant.ts`
|
||||||
|
- `zlt-web/react-web-next/src/services/orders.ts`
|
||||||
|
- `zlt-web/react-web-next/src/utils/tenantCache.ts`
|
||||||
|
- `zlt-web/react-web-next/src/utils/download.ts`
|
||||||
|
- `zlt-web/react-web-next/src/utils/export.ts`
|
||||||
|
- `zlt-web/react-web-next/src/theme.tsx`
|
||||||
|
- `zlt-web/react-web-next/src/theme/modern.less`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*最后更新: 2026-04-01*
|
||||||
@@ -0,0 +1,463 @@
|
|||||||
|
# yingyan 项目 Skill
|
||||||
|
|
||||||
|
**适用范围**: `zlt-web/yingyan`
|
||||||
|
|
||||||
|
**强制要求**: 在该项目中进行 3D 可视化、监控大屏、客户端 Pad、海事场景、地图控制、实时通信相关开发时,默认以本 Skill 为第一约束;除非用户明确要求,否则不要偏离这里定义的结构、边界和实现方式。
|
||||||
|
|
||||||
|
## 1. 项目一句话定义
|
||||||
|
|
||||||
|
`yingyan` 是“鹰眼”3D 可视化管控平台,不是传统后台 CRUD 前端:
|
||||||
|
|
||||||
|
- 以监控大屏、海事场景、3D 地图、Pad 客户端为核心产品形态
|
||||||
|
- 以 Cesium、SSE、WebSocket、深色科技风为核心实现特征
|
||||||
|
- 复用管理端认证、租户、服务接口,但交互模型明显不同于普通后台
|
||||||
|
- 重点不是表单堆砌,而是场景容器、可视化面板、实时状态与地图交互
|
||||||
|
|
||||||
|
## 2. 技术边界
|
||||||
|
|
||||||
|
### 必须遵守
|
||||||
|
|
||||||
|
- React 18
|
||||||
|
- UmiJS 3.5
|
||||||
|
- Ant Design 5
|
||||||
|
- `@ant-design/pro-components` 2.x
|
||||||
|
- TypeScript 5.9,且 `strict: true`
|
||||||
|
- Ant Design 5 `ConfigProvider` 主题体系
|
||||||
|
- Cesium 1.110
|
||||||
|
- `dayjs`
|
||||||
|
|
||||||
|
### 不要擅自做的事
|
||||||
|
|
||||||
|
- 不要把 `react-web-next` 的 Ant Design 4 / Less token 方案直接搬进来
|
||||||
|
- 不要把大屏/地图页改造成普通后台管理页布局
|
||||||
|
- 不要绕开现有 Cesium hook、实时连接 hook、编辑器子系统另造平行实现
|
||||||
|
- 不要把客户端 `/client` 的认证逻辑和管理端 token 逻辑混用
|
||||||
|
|
||||||
|
## 3. 先认清这 6 个核心事实
|
||||||
|
|
||||||
|
### 3.1 这不是普通后台,而是多形态可视化平台
|
||||||
|
|
||||||
|
- 路由同时覆盖管理登录、客户端登录、监控大屏、海事大屏、3D 地图
|
||||||
|
- 页面差异很大,但底层仍共用 Umi、request、租户、部分服务接口
|
||||||
|
- 你做功能前,先判断它属于后台管理、地图场景、客户端 Pad 还是大屏信息展示
|
||||||
|
|
||||||
|
### 3.2 主题体系是 Ant Design 5 + 深色科技风
|
||||||
|
|
||||||
|
- `config/config.ts` 中 `antd: false`
|
||||||
|
- 主题由 `src/theme.tsx` 中的 `ConfigProvider` 接管
|
||||||
|
- 主色、成功色、暗色算法都已统一设定
|
||||||
|
- **不要回退到 Ant Design 4 的 Less 变量主题改法**
|
||||||
|
|
||||||
|
### 3.3 这是双登录体系,不是单一 token 模型
|
||||||
|
|
||||||
|
- 管理端使用:
|
||||||
|
- `sessionStorage.access_token`
|
||||||
|
- `sessionStorage.current_user`
|
||||||
|
- 客户端 `/client` 使用:
|
||||||
|
- `sessionStorage.client_device_sn`
|
||||||
|
- 新逻辑必须先区分当前路径属于管理端还是客户端
|
||||||
|
|
||||||
|
### 3.4 实时数据是基础设施,不是页面临时能力
|
||||||
|
|
||||||
|
- 已有 SSE hook
|
||||||
|
- 已有设备控制 WebSocket service
|
||||||
|
- 已有视频流代理
|
||||||
|
- 页面应消费状态,而不是在 JSX 内到处散写连接生命周期
|
||||||
|
|
||||||
|
### 3.5 3D 能力已经形成子系统,不要单文件硬写
|
||||||
|
|
||||||
|
- 已有 `MapContainer`
|
||||||
|
- 已有 `CesiumContainer`
|
||||||
|
- 已有 `RouteEditor`
|
||||||
|
- 已有 `BoundaryEditor`
|
||||||
|
- 已有 tileset / drone / boat / track / route renderer 等 hook
|
||||||
|
|
||||||
|
### 3.6 后端响应依然优先兼容 `resp_code`
|
||||||
|
|
||||||
|
默认优先兼容:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"resp_code": 0,
|
||||||
|
"resp_msg": "success",
|
||||||
|
"data": {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
结论:
|
||||||
|
|
||||||
|
- 新增 service 时不要发明全新响应契约
|
||||||
|
- 页面层不要直接假设所有接口都已经是纯前端理想结构
|
||||||
|
|
||||||
|
## 4. 目录落位规则
|
||||||
|
|
||||||
|
```text
|
||||||
|
zlt-web/yingyan/
|
||||||
|
├─ config/
|
||||||
|
│ ├─ config.ts
|
||||||
|
│ ├─ proxy.ts
|
||||||
|
│ └─ routes.ts
|
||||||
|
├─ src/
|
||||||
|
│ ├─ app.tsx
|
||||||
|
│ ├─ global.less
|
||||||
|
│ ├─ theme.tsx
|
||||||
|
│ ├─ layouts/
|
||||||
|
│ ├─ pages/
|
||||||
|
│ ├─ services/
|
||||||
|
│ ├─ components/
|
||||||
|
│ ├─ hooks/
|
||||||
|
│ ├─ utils/
|
||||||
|
│ ├─ types/
|
||||||
|
│ └─ typings.d.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
### 你改代码前先判断放哪层
|
||||||
|
|
||||||
|
- 页面容器、页面状态、主交互编排:`src/pages/`
|
||||||
|
- 复用组件、通用可视化面板、平台切换器:`src/components/`
|
||||||
|
- API、实时控制协议、后端接口封装:`src/services/`
|
||||||
|
- 纯工具、缓存、加密、协议辅助:`src/utils/`
|
||||||
|
- 与 React 生命周期强相关的 Cesium / SSE / 状态逻辑:`hooks` 或页面子目录内 hooks
|
||||||
|
- 顶层头部、布局槽位、统一壳层:`src/layouts/`
|
||||||
|
|
||||||
|
### 默认禁止
|
||||||
|
|
||||||
|
- 不要把 viewer 级逻辑直接堆进页面根组件
|
||||||
|
- 不要把页面专属临时状态塞进全局 utils
|
||||||
|
- 不要把通用面板复制到多个页面目录各自维护
|
||||||
|
|
||||||
|
## 5. 配置层规则
|
||||||
|
|
||||||
|
### `config/config.ts`
|
||||||
|
|
||||||
|
你需要知道它控制了:
|
||||||
|
|
||||||
|
- `antd: false`
|
||||||
|
- `routes.ts`
|
||||||
|
- 开发/生产差异化 `publicPath`
|
||||||
|
- `base` 与部署子路径
|
||||||
|
- `dynamicImport.loading`
|
||||||
|
- `process.env.API_PREFIX`
|
||||||
|
- `process.env.APP_BASE`
|
||||||
|
- `process.env.CESIUM_BASE_URL`
|
||||||
|
|
||||||
|
### 配置层修改原则
|
||||||
|
|
||||||
|
- 改部署路径时,同时检查 `base`、`publicPath`、构建脚本
|
||||||
|
- 改 API 访问时,同时检查 `proxy.ts` 与 `src/app.tsx` 中 request prefix
|
||||||
|
- 改 Cesium 资源路径时,不要绕开 `CESIUM_BASE_URL`
|
||||||
|
- 改主题时,优先改 `src/theme.tsx` 的 `ConfigProvider` 配置,而不是退回旧体系
|
||||||
|
|
||||||
|
### `config/proxy.ts`
|
||||||
|
|
||||||
|
已存在的代理重点:
|
||||||
|
|
||||||
|
- `/api-`
|
||||||
|
- `/goflymodel`
|
||||||
|
- `/rtc`
|
||||||
|
- `/terraform`
|
||||||
|
|
||||||
|
新增代理前先问自己:
|
||||||
|
|
||||||
|
- 这是开发期代理,还是正式线上路径?
|
||||||
|
- 是否应由网关、Nginx 或后端服务接管,而不是前端本地代理?
|
||||||
|
|
||||||
|
### `config/routes.ts`
|
||||||
|
|
||||||
|
核心页面包括:
|
||||||
|
|
||||||
|
- `/user/login`
|
||||||
|
- `/client/login`
|
||||||
|
- `/client`
|
||||||
|
- `/dashboard`
|
||||||
|
- `/maritime`
|
||||||
|
- `/map3d`
|
||||||
|
|
||||||
|
规则:
|
||||||
|
|
||||||
|
- 管理登录与客户端登录不挂主布局
|
||||||
|
- 主应用默认挂 `@/layouts/BlankLayout`
|
||||||
|
- 不要把地图页和大屏页硬改造成 ProLayout 导航壳层
|
||||||
|
|
||||||
|
## 6. 页面开发规则
|
||||||
|
|
||||||
|
### 页面职责
|
||||||
|
|
||||||
|
页面负责:
|
||||||
|
|
||||||
|
- 组织场景容器、面板、头部插槽、可视化区块
|
||||||
|
- 管理页面级状态
|
||||||
|
- 组合 hook 与 service
|
||||||
|
- 控制子组件装配关系
|
||||||
|
|
||||||
|
页面不负责:
|
||||||
|
|
||||||
|
- 直接维护大量 viewer 底层实体生命周期
|
||||||
|
- 到处手搓 SSE / WebSocket 连接
|
||||||
|
- 把复杂地图交互全部堆在单个组件中
|
||||||
|
|
||||||
|
### 不同页面类型的默认思路
|
||||||
|
|
||||||
|
#### 大屏页
|
||||||
|
|
||||||
|
- 强调信息区块、KPI、卡片、视觉层次
|
||||||
|
- 组件通常拆在对应页面的 `components/`
|
||||||
|
|
||||||
|
#### 地图页
|
||||||
|
|
||||||
|
- 强调容器 + 面板 + hook 分层
|
||||||
|
- viewer、实体、轨迹、绘制、加载逻辑优先下沉
|
||||||
|
|
||||||
|
#### 客户端页
|
||||||
|
|
||||||
|
- 强调沉浸式交互与状态联动
|
||||||
|
- 登录、导航、遥测、路线预览优先在 `src/pages/client/` 内自洽管理
|
||||||
|
|
||||||
|
## 7. 组件开发规则
|
||||||
|
|
||||||
|
### 统一组件规范
|
||||||
|
|
||||||
|
- 一律函数组件 + Hooks
|
||||||
|
- Props 必须显式定义 TypeScript 类型
|
||||||
|
- 复杂视觉页面拆成容器层、面板层、hook 层
|
||||||
|
- 复用价值高的场景组件优先抽离,不要复制实现
|
||||||
|
|
||||||
|
### 优先复用的现成组件
|
||||||
|
|
||||||
|
- `TenantScopeFilter`
|
||||||
|
- `PlatformSwitcher`
|
||||||
|
- `PageLoading`
|
||||||
|
|
||||||
|
### 地图/大屏组件设计原则
|
||||||
|
|
||||||
|
- 容器组件负责装配
|
||||||
|
- 面板组件负责展示和局部交互
|
||||||
|
- hook 负责副作用、场景对象、连接管理
|
||||||
|
- service 负责远端协议与接口
|
||||||
|
|
||||||
|
## 8. Service 层规则
|
||||||
|
|
||||||
|
### 基本要求
|
||||||
|
|
||||||
|
- 所有接口默认进入 `src/services/`
|
||||||
|
- 一个文件对应一个业务域
|
||||||
|
- 统一封装请求、参数映射、返回兼容
|
||||||
|
- 需要实时控制时,区分 HTTP service 和 WebSocket service
|
||||||
|
|
||||||
|
### 常见 service 领域
|
||||||
|
|
||||||
|
- `login.ts`
|
||||||
|
- `device.ts`
|
||||||
|
- `dashboard.ts`
|
||||||
|
- `mission.ts`
|
||||||
|
- `boatRoute.ts`
|
||||||
|
- `waterBoundary.ts`
|
||||||
|
- `threeDModel.ts`
|
||||||
|
- `maritime.ts`
|
||||||
|
- `tenant.ts`
|
||||||
|
- `deviceControlWs.ts`
|
||||||
|
|
||||||
|
### Service 层该做什么
|
||||||
|
|
||||||
|
- 管理接口路径和请求方法
|
||||||
|
- 隔离页面与后端协议细节
|
||||||
|
- 统一兼容 `resp_code / resp_msg / data`
|
||||||
|
- 为地图/航线/边界/模型等能力提供清晰 API
|
||||||
|
|
||||||
|
### Service 层不该做什么
|
||||||
|
|
||||||
|
- 不要塞入重 UI 逻辑
|
||||||
|
- 不要接管页面状态机
|
||||||
|
- 不要在 service 里重新实现布局或页面判断
|
||||||
|
|
||||||
|
## 9. Hooks 与实时通信规则
|
||||||
|
|
||||||
|
### 什么时候放 hooks
|
||||||
|
|
||||||
|
- 需要跟 React 生命周期绑定
|
||||||
|
- 需要管理连接、清理、副作用
|
||||||
|
- 需要复用 Cesium viewer、实体、轨迹、绘制逻辑
|
||||||
|
|
||||||
|
### 已有重点 hook 类型
|
||||||
|
|
||||||
|
- SSE:`useDroneSSE`、`useBoatSSE`、`useClientSSE`
|
||||||
|
- Tileset:`useTilesetLoader`
|
||||||
|
- 船舶/无人机轨迹与渲染:相关 Cesium hook
|
||||||
|
- 路线编辑:`useRouteDrawing`、`useCesiumRouteRenderer`、`useRouteValidation`
|
||||||
|
- 边界编辑:`useBoundaryDrawing`、`useCesiumBoundaryRenderer`
|
||||||
|
|
||||||
|
### 实时能力规则
|
||||||
|
|
||||||
|
- 建立连接、断线重连、释放资源必须封装在 hook 或 service 中
|
||||||
|
- 页面只消费状态与回调,不要直接到处 new 连接
|
||||||
|
- 组件卸载时必须有清理逻辑
|
||||||
|
|
||||||
|
## 10. 布局与主题规则
|
||||||
|
|
||||||
|
### 布局
|
||||||
|
|
||||||
|
`src/layouts/BlankLayout.tsx` 负责:
|
||||||
|
|
||||||
|
- 顶部栏
|
||||||
|
- 平台切换
|
||||||
|
- 租户过滤
|
||||||
|
- 用户菜单
|
||||||
|
- 大屏 / 海事 / 地图头部插槽
|
||||||
|
|
||||||
|
规则:
|
||||||
|
|
||||||
|
- `/dashboard`、`/maritime` 走大屏标题模式
|
||||||
|
- `/map3d` 通过 header slot 注入地图专属头部内容
|
||||||
|
- 不要把地图专属头部逻辑硬塞进普通布局分支
|
||||||
|
|
||||||
|
### 主题
|
||||||
|
|
||||||
|
主题核心在 `src/theme.tsx`:
|
||||||
|
|
||||||
|
- `ConfigProvider`
|
||||||
|
- 深色算法 `antdTheme.darkAlgorithm`
|
||||||
|
- 主色 `#00d4ff`
|
||||||
|
- 成功色 `#00ff88`
|
||||||
|
|
||||||
|
样式开发要求:
|
||||||
|
|
||||||
|
- 保持深色科技风一致性
|
||||||
|
- 强调玻璃面板、边框高亮、信息层次
|
||||||
|
- 浮层和地图覆盖物要兼顾可读性与点击区域
|
||||||
|
|
||||||
|
## 11. 登录、租户、客户端三条红线
|
||||||
|
|
||||||
|
### 登录
|
||||||
|
|
||||||
|
- 管理端登录页:`src/pages/user/Login`
|
||||||
|
- 客户端登录页:`src/pages/client/Login`
|
||||||
|
- 管理端和客户端认证逻辑必须区分处理
|
||||||
|
|
||||||
|
禁止:
|
||||||
|
|
||||||
|
- 把 `/client` 也按后台 token 模式处理
|
||||||
|
- 把后台未授权跳转逻辑直接复用到客户端页面
|
||||||
|
|
||||||
|
### 租户
|
||||||
|
|
||||||
|
- 管理端与大屏数据如果受租户影响,优先接入 `TenantScopeFilter`
|
||||||
|
- 缓存与 Token 联动优先沿用 `tenantCache`
|
||||||
|
|
||||||
|
禁止:
|
||||||
|
|
||||||
|
- 每个页面各自维护租户树副本
|
||||||
|
- 每个大屏组件私自再造租户过滤协议
|
||||||
|
|
||||||
|
### 客户端
|
||||||
|
|
||||||
|
- `/client` 下逻辑优先在该目录内部自洽封装
|
||||||
|
- 导航、遥测、预览、设备态等优先下沉 hook
|
||||||
|
|
||||||
|
## 12. 3D / 地图子系统边界
|
||||||
|
|
||||||
|
### 重点目录
|
||||||
|
|
||||||
|
- `src/pages/map3d/components/MapContainer/3d/`
|
||||||
|
- `src/pages/map3d/components/RouteEditor/`
|
||||||
|
- `src/pages/map3d/components/BoundaryEditor/`
|
||||||
|
- `src/services/threeDModel.ts`
|
||||||
|
|
||||||
|
### 已有核心能力
|
||||||
|
|
||||||
|
- 3D Tiles 模型加载
|
||||||
|
- 路线绘制与渲染
|
||||||
|
- 边界绘制与渲染
|
||||||
|
- 船舶轨迹渲染
|
||||||
|
- 相机飞行与聚焦
|
||||||
|
- 实时点位刷新
|
||||||
|
|
||||||
|
### 开发规则
|
||||||
|
|
||||||
|
- viewer 级副作用优先集中在容器/hook 层
|
||||||
|
- 不要在多个组件里重复创建全局场景逻辑
|
||||||
|
- 先查现有 RouteEditor / BoundaryEditor 基础设施,再决定是否扩展
|
||||||
|
|
||||||
|
## 13. TypeScript 规则
|
||||||
|
|
||||||
|
- 必须尊重 `strict: true`
|
||||||
|
- 复杂场景对象必须显式类型化
|
||||||
|
- 航点、边界、模型、设备状态、导航状态优先抽到类型文件
|
||||||
|
- 全局和场景类型优先查看:
|
||||||
|
- `src/typings.d.ts`
|
||||||
|
- `src/types/`
|
||||||
|
- 各子系统自己的 `types.ts`
|
||||||
|
|
||||||
|
严格禁止:
|
||||||
|
|
||||||
|
- `as any`
|
||||||
|
- `@ts-ignore`
|
||||||
|
- `@ts-expect-error`
|
||||||
|
|
||||||
|
## 14. 典型工作流
|
||||||
|
|
||||||
|
### 新增地图/3D 功能
|
||||||
|
|
||||||
|
1. 先判断属于容器、面板、hook 还是 service
|
||||||
|
2. 查现有 tileset / route / boundary / track 相关基础设施
|
||||||
|
3. 优先复用已有 hook 与 renderer
|
||||||
|
4. 补充必要的 service 封装
|
||||||
|
5. 做好卸载清理、实体清理、事件解绑
|
||||||
|
6. 保持深色科技风一致
|
||||||
|
|
||||||
|
### 新增大屏区块
|
||||||
|
|
||||||
|
1. 优先放对应页面 `components/`
|
||||||
|
2. 保持卡片、信息带、面板的视觉语言统一
|
||||||
|
3. 数据获取放 service,状态组装放页面或 hook
|
||||||
|
|
||||||
|
### 新增客户端能力
|
||||||
|
|
||||||
|
1. 优先放 `src/pages/client/` 内部
|
||||||
|
2. 先判断是否依赖设备号登录态
|
||||||
|
3. 导航/预览/遥测逻辑优先用 hook 管理
|
||||||
|
|
||||||
|
## 15. 决策清单
|
||||||
|
|
||||||
|
动手前自检:
|
||||||
|
|
||||||
|
- 当前逻辑是管理端、客户端、大屏还是地图页?
|
||||||
|
- 是否误用了后台 token 逻辑到 `/client`?
|
||||||
|
- 是否已有可复用的 Cesium hook、编辑器或 service?
|
||||||
|
- 这段逻辑应放 panel、hook、service 还是页面容器?
|
||||||
|
- 是否仍然在 Ant Design 5 + ConfigProvider + 深色科技风边界内?
|
||||||
|
- 是否兼容 `resp_code / resp_msg / data`?
|
||||||
|
- 是否考虑了连接清理、资源释放、viewer 生命周期?
|
||||||
|
|
||||||
|
## 16. 明确禁止事项
|
||||||
|
|
||||||
|
- 按 `react-web-next` 的 Antd4 思路改这个项目主题
|
||||||
|
- 在地图页重复造 viewer 生命周期管理
|
||||||
|
- 把 `/client` 与后台登录态混为一谈
|
||||||
|
- 把复杂实时连接逻辑直接塞进 JSX 页面
|
||||||
|
- 新增浅色后台风格破坏整体科技感
|
||||||
|
- 绕过现有 Cesium hook 和编辑器基础设施重新手搓一套平行系统
|
||||||
|
|
||||||
|
## 17. 优先参考文件
|
||||||
|
|
||||||
|
- `zlt-web/yingyan/config/config.ts`
|
||||||
|
- `zlt-web/yingyan/config/routes.ts`
|
||||||
|
- `zlt-web/yingyan/config/proxy.ts`
|
||||||
|
- `zlt-web/yingyan/src/app.tsx`
|
||||||
|
- `zlt-web/yingyan/src/theme.tsx`
|
||||||
|
- `zlt-web/yingyan/src/global.less`
|
||||||
|
- `zlt-web/yingyan/src/layouts/BlankLayout.tsx`
|
||||||
|
- `zlt-web/yingyan/src/components/TenantScopeFilter/index.tsx`
|
||||||
|
- `zlt-web/yingyan/src/components/PlatformSwitcher/index.tsx`
|
||||||
|
- `zlt-web/yingyan/src/services/device.ts`
|
||||||
|
- `zlt-web/yingyan/src/services/threeDModel.ts`
|
||||||
|
- `zlt-web/yingyan/src/services/deviceControlWs.ts`
|
||||||
|
- `zlt-web/yingyan/src/services/boatRoute.ts`
|
||||||
|
- `zlt-web/yingyan/src/services/waterBoundary.ts`
|
||||||
|
- `zlt-web/yingyan/src/pages/map3d/components/MapContainer/CesiumContainer.tsx`
|
||||||
|
- `zlt-web/yingyan/src/pages/map3d/components/RouteEditor/index.tsx`
|
||||||
|
- `zlt-web/yingyan/src/pages/map3d/components/BoundaryEditor/index.tsx`
|
||||||
|
- `zlt-web/yingyan/src/pages/client/index.tsx`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*最后更新: 2026-04-01*
|
||||||
+108
@@ -0,0 +1,108 @@
|
|||||||
|
package com.central.coupon.config;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程分销商配置
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "ctrip.distributor")
|
||||||
|
public class CtripDistributorConfig {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分销商AID
|
||||||
|
*/
|
||||||
|
private Long aid;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分销商SID
|
||||||
|
*/
|
||||||
|
private Long sid;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分销商密钥
|
||||||
|
*/
|
||||||
|
private String key;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 认证URL
|
||||||
|
*/
|
||||||
|
private String authUrl;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 刷新Token URL
|
||||||
|
*/
|
||||||
|
private String refreshUrl;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 业务API URL
|
||||||
|
*/
|
||||||
|
private String apiUrl;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 语言地区
|
||||||
|
*/
|
||||||
|
private String locale;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 货币代码
|
||||||
|
*/
|
||||||
|
private String currency;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 各接口icode配置
|
||||||
|
*/
|
||||||
|
private IcodeConfig icode;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public static class IcodeConfig {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 产品详情接口icode
|
||||||
|
*/
|
||||||
|
private String productDetail;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取下单填写信息接口icode
|
||||||
|
*/
|
||||||
|
private String bookInfo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建订单接口icode
|
||||||
|
*/
|
||||||
|
private String book;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消验证接口icode
|
||||||
|
*/
|
||||||
|
private String cancelVerify;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消订单接口icode
|
||||||
|
*/
|
||||||
|
private String cancel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订单详情查询接口icode
|
||||||
|
*/
|
||||||
|
private String bookingDetail;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 可订检查接口icode
|
||||||
|
*/
|
||||||
|
private String checkAvailability;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 沙箱测试-订单退订(携程发起)接口icode
|
||||||
|
*/
|
||||||
|
private String simulateCancel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 沙箱测试-人工出票/退订确认/凭证变更接口icode
|
||||||
|
*/
|
||||||
|
private String simulateConfirm;
|
||||||
|
}
|
||||||
|
}
|
||||||
+128
@@ -0,0 +1,128 @@
|
|||||||
|
package com.central.coupon.controller;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import com.central.coupon.entity.CtripDistOrder;
|
||||||
|
import com.central.coupon.mapper.CtripDistOrderMapper;
|
||||||
|
import com.central.coupon.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.util.StringUtils;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/ctrip/dist/order")
|
||||||
|
@Tag(name = "携程分销订单管理")
|
||||||
|
public class CtripDistOrderController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ICtripDistOrderService ctripDistOrderService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CtripDistOrderMapper ctripDistOrderMapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分页查询携程分销订单列表
|
||||||
|
*/
|
||||||
|
@Operation(summary = "分页查询携程分销订单列表")
|
||||||
|
@GetMapping("/list")
|
||||||
|
public Result<Map<String, Object>> listCtripDistOrders(
|
||||||
|
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
|
||||||
|
@Parameter(description = "每页数量") @RequestParam(defaultValue = "20") Integer limit,
|
||||||
|
@Parameter(description = "本地订单号") @RequestParam(required = false) String orderNo,
|
||||||
|
@Parameter(description = "携程订单ID") @RequestParam(required = false) Long ctripOrderId,
|
||||||
|
@Parameter(description = "携程产品ID") @RequestParam(required = false) Long ctripProductId,
|
||||||
|
@Parameter(description = "携程订单状态") @RequestParam(required = false) String ctripOrderStatus,
|
||||||
|
@Parameter(description = "核销状态") @RequestParam(required = false) Integer consumeStatus,
|
||||||
|
@Parameter(description = "退款状态") @RequestParam(required = false) Integer refundStatus,
|
||||||
|
@Parameter(description = "租户ID") @RequestParam(required = false) String tenantId) {
|
||||||
|
log.info("分页查询携程分销订单列表,page: {}, limit: {}, orderNo: {}", page, limit, orderNo);
|
||||||
|
try {
|
||||||
|
LambdaQueryWrapper<CtripDistOrder> queryWrapper = new LambdaQueryWrapper<>();
|
||||||
|
queryWrapper.eq(CtripDistOrder::getDeleted, 0);
|
||||||
|
if (StringUtils.hasText(orderNo)) {
|
||||||
|
queryWrapper.like(CtripDistOrder::getOrderNo, orderNo);
|
||||||
|
}
|
||||||
|
if (ctripOrderId != null) {
|
||||||
|
queryWrapper.eq(CtripDistOrder::getCtripOrderId, ctripOrderId);
|
||||||
|
}
|
||||||
|
if (ctripProductId != null) {
|
||||||
|
queryWrapper.eq(CtripDistOrder::getCtripProductId, ctripProductId);
|
||||||
|
}
|
||||||
|
if (StringUtils.hasText(ctripOrderStatus)) {
|
||||||
|
queryWrapper.eq(CtripDistOrder::getCtripOrderStatus, ctripOrderStatus);
|
||||||
|
}
|
||||||
|
if (consumeStatus != null) {
|
||||||
|
queryWrapper.eq(CtripDistOrder::getConsumeStatus, consumeStatus);
|
||||||
|
}
|
||||||
|
if (refundStatus != null) {
|
||||||
|
queryWrapper.eq(CtripDistOrder::getRefundStatus, refundStatus);
|
||||||
|
}
|
||||||
|
if (StringUtils.hasText(tenantId)) {
|
||||||
|
queryWrapper.eq(CtripDistOrder::getTenantId, tenantId);
|
||||||
|
}
|
||||||
|
queryWrapper.orderByDesc(CtripDistOrder::getCreateTime);
|
||||||
|
|
||||||
|
Page<CtripDistOrder> pageParam = new Page<>(page, limit);
|
||||||
|
IPage<CtripDistOrder> pageResult = ctripDistOrderMapper.selectPage(pageParam, queryWrapper);
|
||||||
|
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("data", pageResult.getRecords());
|
||||||
|
result.put("count", pageResult.getTotal());
|
||||||
|
result.put("page", page);
|
||||||
|
result.put("limit", limit);
|
||||||
|
return Result.succeed(result);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("查询携程分销订单列表异常", e);
|
||||||
|
return Result.failed("查询失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建携程分销订单(被order-center通过Feign调用)
|
||||||
|
*/
|
||||||
|
@PostMapping("/create")
|
||||||
|
public Result<String> createCtripDistOrder(@RequestBody Map<String, Object> params) {
|
||||||
|
String orderNo = (String) params.get("orderNo");
|
||||||
|
String orderAmount = (String) params.get("orderAmount");
|
||||||
|
Long ctripProductId = Long.valueOf(params.get("ctripProductId").toString());
|
||||||
|
String tenantId = (String) params.get("tenantId");
|
||||||
|
String mobile = params.get("mobile") != null ? params.get("mobile").toString() : null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
ctripDistOrderService.createCtripDistOrder(orderNo, orderAmount, ctripProductId, tenantId, mobile);
|
||||||
|
return Result.succeed("携程分销订单创建成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("创建携程分销订单失败", e);
|
||||||
|
return Result.failed("创建失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 退订携程分销订单
|
||||||
|
*/
|
||||||
|
@PostMapping("/cancel/{orderNo}")
|
||||||
|
public Result<String> cancelCtripDistOrder(
|
||||||
|
@PathVariable String orderNo,
|
||||||
|
@RequestParam(defaultValue = "用户申请退订") String reason) {
|
||||||
|
boolean success = ctripDistOrderService.cancelCtripDistOrder(orderNo, reason);
|
||||||
|
return success ? Result.succeed("退订成功") : Result.failed("退订失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询携程分销订单详情
|
||||||
|
*/
|
||||||
|
@GetMapping("/{orderNo}")
|
||||||
|
public Result<CtripDistOrder> getCtripDistOrder(@PathVariable String orderNo) {
|
||||||
|
return Result.succeed(ctripDistOrderService.getByOrderNo(orderNo));
|
||||||
|
}
|
||||||
|
}
|
||||||
+708
@@ -0,0 +1,708 @@
|
|||||||
|
package com.central.coupon.controller;
|
||||||
|
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import com.central.coupon.model.CtripDistBookRequest;
|
||||||
|
import com.central.coupon.model.CtripDistBookResponse;
|
||||||
|
import com.central.coupon.model.CtripDistBookingDetailResponse;
|
||||||
|
import com.central.coupon.model.CtripDistCancelResponse;
|
||||||
|
import com.central.coupon.model.CtripDistCancelVerifyResponse;
|
||||||
|
import com.central.coupon.service.ICtripDistApiService;
|
||||||
|
import com.central.coupon.service.ICtripDistTokenService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
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.*;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程分销商接口沙箱测试
|
||||||
|
* 用途:逐个调试携程分销商API,确认连通性和返回格式
|
||||||
|
* 注意:仅用于测试环境,生产环境应禁用或加权限控制
|
||||||
|
*
|
||||||
|
* 核心设计:
|
||||||
|
* - 调用 bookInfo 接口后,问卷模板按 productId 缓存
|
||||||
|
* - 后续的可订检查/创建订单自动从缓存中取问卷模板
|
||||||
|
* - 用户只需传 questionCode → 答案值,系统自动匹配 questionID/questionTitle
|
||||||
|
* - 不同产品的测试步骤差异(字段不同、数量不同)全部通过参数控制
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/ctrip/dist/test")
|
||||||
|
@Tag(name = "携程分销商接口测试")
|
||||||
|
public class CtripDistTestController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ICtripDistApiService ctripDistApiService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ICtripDistTokenService ctripDistTokenService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private com.central.coupon.config.CtripDistributorConfig ctripDistributorConfig;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* bookInfo 缓存:key=productId, value=bookInfo完整返回
|
||||||
|
* 调用 bookInfo 接口后自动缓存,后续接口直接使用
|
||||||
|
*/
|
||||||
|
private final Map<Long, Map<String, Object>> bookInfoCache = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
// ==================== -1. 配置诊断 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 诊断当前分销商配置
|
||||||
|
* 用途:确认Nacos配置是否被正确注入(key脱敏显示)
|
||||||
|
*
|
||||||
|
* 调用示例:GET /ctrip/dist/test/config
|
||||||
|
*/
|
||||||
|
@GetMapping("/config")
|
||||||
|
@Operation(summary = "诊断分销商配置")
|
||||||
|
public Result<Map<String, Object>> testConfig() {
|
||||||
|
Map<String, Object> data = new LinkedHashMap<>();
|
||||||
|
data.put("aid", ctripDistributorConfig.getAid());
|
||||||
|
data.put("sid", ctripDistributorConfig.getSid());
|
||||||
|
data.put("key", ctripDistributorConfig.getKey() != null
|
||||||
|
? ctripDistributorConfig.getKey().substring(0, Math.min(4, ctripDistributorConfig.getKey().length())) + "****"
|
||||||
|
: "null");
|
||||||
|
data.put("authUrl", ctripDistributorConfig.getAuthUrl());
|
||||||
|
data.put("refreshUrl", ctripDistributorConfig.getRefreshUrl());
|
||||||
|
data.put("apiUrl", ctripDistributorConfig.getApiUrl());
|
||||||
|
data.put("locale", ctripDistributorConfig.getLocale());
|
||||||
|
data.put("currency", ctripDistributorConfig.getCurrency());
|
||||||
|
if (ctripDistributorConfig.getIcode() != null) {
|
||||||
|
Map<String, Object> icode = new LinkedHashMap<>();
|
||||||
|
icode.put("productDetail", ctripDistributorConfig.getIcode().getProductDetail());
|
||||||
|
icode.put("bookInfo", ctripDistributorConfig.getIcode().getBookInfo());
|
||||||
|
icode.put("book", ctripDistributorConfig.getIcode().getBook());
|
||||||
|
icode.put("cancelVerify", ctripDistributorConfig.getIcode().getCancelVerify());
|
||||||
|
icode.put("cancel", ctripDistributorConfig.getIcode().getCancel());
|
||||||
|
icode.put("bookingDetail", ctripDistributorConfig.getIcode().getBookingDetail());
|
||||||
|
data.put("icode", icode);
|
||||||
|
} else {
|
||||||
|
data.put("icode", "null - icode未配置!");
|
||||||
|
}
|
||||||
|
return Result.succeed(data, "当前分销商配置");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 0. Token测试 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试获取Token
|
||||||
|
* 用途:验证aid/sid/key配置是否正确,Token能否正常获取
|
||||||
|
*
|
||||||
|
* 调用示例:POST /ctrip/dist/test/token
|
||||||
|
*/
|
||||||
|
@PostMapping("/token")
|
||||||
|
@Operation(summary = "测试获取Token")
|
||||||
|
public Result<Map<String, Object>> testGetToken() {
|
||||||
|
log.info("===== 测试获取携程分销商Token =====");
|
||||||
|
try {
|
||||||
|
String token = ctripDistTokenService.getAccessToken();
|
||||||
|
Map<String, Object> data = new LinkedHashMap<>();
|
||||||
|
data.put("accessToken", token);
|
||||||
|
data.put("tokenLength", token != null ? token.length() : 0);
|
||||||
|
data.put("message", "Token获取成功");
|
||||||
|
log.info("Token获取成功,长度: {}", token != null ? token.length() : 0);
|
||||||
|
return Result.succeed(data, "Token获取成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Token获取失败", e);
|
||||||
|
return Result.failed("Token获取失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 1. 获取产品详情 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试获取产品详情
|
||||||
|
* 用途:根据productId获取产品信息,包含packageID和resourceID
|
||||||
|
* 后续下单需要用到返回的packageID和resourceID
|
||||||
|
*
|
||||||
|
* 调用示例:GET /ctrip/dist/test/product-detail?productId=12345678
|
||||||
|
*/
|
||||||
|
@GetMapping("/product-detail")
|
||||||
|
@Operation(summary = "1.获取产品详情")
|
||||||
|
public Result<Map<String, Object>> testProductDetail(@RequestParam Long productId) {
|
||||||
|
log.info("===== 测试获取产品详情,productId: {} =====", productId);
|
||||||
|
try {
|
||||||
|
Map<String, Object> result = ctripDistApiService.getProductDetail(productId);
|
||||||
|
log.info("产品详情返回: {}", result);
|
||||||
|
return Result.succeed(result, "获取产���详情成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取产品详情失败,productId: {}", productId, e);
|
||||||
|
return Result.failed("获取产品详情失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 2. 获取下单填写信息(会自动缓存) ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试获取下单填写信息
|
||||||
|
* 用途:下单前查询该产品需要填写哪些字段(如手机号、身份证、英文姓名等)
|
||||||
|
* 调用成功后会按 productId 缓存结果,后续可订检查/创建订单自动使用
|
||||||
|
* 需要先调用接口1获取packageId和resourceId
|
||||||
|
*
|
||||||
|
* 调用示例:GET /ctrip/dist/test/book-info?productId=12345678&packageId=37326707&resourceId=37326710
|
||||||
|
*/
|
||||||
|
@GetMapping("/book-info")
|
||||||
|
@Operation(summary = "2.获取下单填写信息(自动缓存)")
|
||||||
|
public Result<Map<String, Object>> testBookInfo(
|
||||||
|
@RequestParam Long productId,
|
||||||
|
@RequestParam Long packageId,
|
||||||
|
@RequestParam Long resourceId) {
|
||||||
|
log.info("===== 测试获取下单填写信息,productId: {}, packageId: {}, resourceId: {} =====",
|
||||||
|
productId, packageId, resourceId);
|
||||||
|
try {
|
||||||
|
Map<String, Object> result = ctripDistApiService.getBookInfo(productId, packageId, resourceId);
|
||||||
|
log.info("下单填写信息返回: {}", result);
|
||||||
|
|
||||||
|
// 缓存 bookInfo 结果
|
||||||
|
bookInfoCache.put(productId, result);
|
||||||
|
log.info("bookInfo已缓存,productId: {},后续接口将自动使用", productId);
|
||||||
|
|
||||||
|
return Result.succeed(result, "获取下单填写信息成功(已缓存)");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取下单填写信息失败", e);
|
||||||
|
return Result.failed("获取下单填写信息失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查看当前缓存的bookInfo
|
||||||
|
* 用途:查看某个产品已缓存的问卷模板,方便确认需要填哪些字段
|
||||||
|
*
|
||||||
|
* 调用示例:GET /ctrip/dist/test/book-info/cache?productId=39098283
|
||||||
|
*/
|
||||||
|
@GetMapping("/book-info/cache")
|
||||||
|
@Operation(summary = "2.1 查看缓存的bookInfo")
|
||||||
|
public Result<Map<String, Object>> getCachedBookInfo(@RequestParam Long productId) {
|
||||||
|
Map<String, Object> cached = bookInfoCache.get(productId);
|
||||||
|
if (cached == null) {
|
||||||
|
return Result.failed("productId=" + productId + " 的bookInfo未缓存,请先调用接口2获取");
|
||||||
|
}
|
||||||
|
// 额外提取问卷模板摘要方便查看
|
||||||
|
Map<String, Object> result = new LinkedHashMap<>();
|
||||||
|
result.put("productId", productId);
|
||||||
|
result.put("questionTemplate", extractQuestionTemplate(cached));
|
||||||
|
result.put("fullResponse", cached);
|
||||||
|
return Result.succeed(result, "缓存的bookInfo");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 2.5 可订检查 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试可订检查
|
||||||
|
* 用途:下单前检查资源是否可预订
|
||||||
|
* 前提:必须先调用接口2获取bookInfo(已自动缓存)
|
||||||
|
*
|
||||||
|
* passengers中每个出行人只需传 questionCode → 答案值,
|
||||||
|
* 系统会自动从缓存的bookInfo中匹配questionID和questionTitle
|
||||||
|
*
|
||||||
|
* 调用示例:POST /ctrip/dist/test/check-availability
|
||||||
|
*
|
||||||
|
* 产品2示例(中文姓名+身份证,2出行人):
|
||||||
|
* {
|
||||||
|
* "productId": xxx,
|
||||||
|
* "packageId": xxx,
|
||||||
|
* "resourceId": xxx,
|
||||||
|
* "price": 68.00,
|
||||||
|
* "quantity": 2,
|
||||||
|
* "passengers": [
|
||||||
|
* {"P_NAME": "杜超", "P_ID_CARD": "120101199003076531"},
|
||||||
|
* {"P_NAME": "张三", "P_ID_CARD": "120101199003076532"}
|
||||||
|
* ]
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* 产品3示例(英文姓名,quantity=2但只需1个出行人):
|
||||||
|
* {
|
||||||
|
* "productId": 39098283,
|
||||||
|
* "packageId": xxx,
|
||||||
|
* "resourceId": xxx,
|
||||||
|
* "price": 68.00,
|
||||||
|
* "quantity": 2,
|
||||||
|
* "passengers": [
|
||||||
|
* {"P_FIRSTCNAME": "Chao", "P_LASTCNAME": "Du"}
|
||||||
|
* ]
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
@PostMapping("/check-availability")
|
||||||
|
@Operation(summary = "2.5 可订检查")
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public Result<Map<String, Object>> testCheckAvailability(@RequestBody Map<String, Object> params) {
|
||||||
|
log.info("===== 测试可订检查,params: {} =====", params);
|
||||||
|
try {
|
||||||
|
Long productId = Long.valueOf(params.get("productId").toString());
|
||||||
|
Long packageId = Long.valueOf(params.get("packageId").toString());
|
||||||
|
Long resourceId = Long.valueOf(params.get("resourceId").toString());
|
||||||
|
BigDecimal price = new BigDecimal(params.get("price").toString());
|
||||||
|
String contactName = params.getOrDefault("contactName", "杜超").toString();
|
||||||
|
String contactMobile = params.getOrDefault("contactMobile", "18222892722").toString();
|
||||||
|
String contactEmail = params.getOrDefault("contactEmail", "1098974449@qq.com").toString();
|
||||||
|
|
||||||
|
// 从缓存获取问卷模板
|
||||||
|
List<Map<String, Object>> questionTemplate = getQuestionTemplate(productId);
|
||||||
|
|
||||||
|
// 解析出行人问卷答案
|
||||||
|
List<List<CtripDistBookRequest.QuestionAnswer>> passengerAnswers =
|
||||||
|
parsePassengerAnswers(params, questionTemplate);
|
||||||
|
|
||||||
|
// quantity 独立于出行人数量
|
||||||
|
int quantity = params.get("quantity") != null
|
||||||
|
? Integer.parseInt(params.get("quantity").toString())
|
||||||
|
: passengerAnswers.size();
|
||||||
|
|
||||||
|
String useDate = params.getOrDefault("useDate",
|
||||||
|
LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))).toString();
|
||||||
|
|
||||||
|
String distributorOrderId = "CHECK_" + System.currentTimeMillis();
|
||||||
|
CtripDistBookRequest request = buildTestBookRequest(
|
||||||
|
distributorOrderId, productId, packageId, resourceId,
|
||||||
|
price, quantity, useDate, contactName, contactMobile, contactEmail,
|
||||||
|
passengerAnswers);
|
||||||
|
|
||||||
|
boolean available = ctripDistApiService.checkAvailability(request);
|
||||||
|
Map<String, Object> data = new LinkedHashMap<>();
|
||||||
|
data.put("available", available);
|
||||||
|
data.put("quantity", quantity);
|
||||||
|
data.put("passengerCount", passengerAnswers.size());
|
||||||
|
data.put("message", available ? "可预订" : "不可预订");
|
||||||
|
log.info("可订检查结果: {}, 购买数量: {}, 出行人数: {}", available, quantity, passengerAnswers.size());
|
||||||
|
return Result.succeed(data, available ? "可预订" : "不可预订");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("可订检查失败", e);
|
||||||
|
return Result.failed("可订检查失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 3. 创建携程订单 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试创建携程订单
|
||||||
|
* 前提:必须先调用接口2获取bookInfo(已自动缓存)
|
||||||
|
* 参数格式与可订检查完全一致
|
||||||
|
*
|
||||||
|
* 调用示例:POST /ctrip/dist/test/book
|
||||||
|
* Body: 与可订检查接口相同
|
||||||
|
*/
|
||||||
|
@PostMapping("/book")
|
||||||
|
@Operation(summary = "3.创建携程订单")
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public Result<CtripDistBookResponse> testCreateOrder(@RequestBody Map<String, Object> params) {
|
||||||
|
log.info("===== 测试创建携程订单,params: {} =====", params);
|
||||||
|
try {
|
||||||
|
Long productId = Long.valueOf(params.get("productId").toString());
|
||||||
|
Long packageId = Long.valueOf(params.get("packageId").toString());
|
||||||
|
Long resourceId = Long.valueOf(params.get("resourceId").toString());
|
||||||
|
BigDecimal price = new BigDecimal(params.get("price").toString());
|
||||||
|
String contactName = params.getOrDefault("contactName", "杜超").toString();
|
||||||
|
String contactMobile = params.getOrDefault("contactMobile", "18222892722").toString();
|
||||||
|
String contactEmail = params.getOrDefault("contactEmail", "1098974449@qq.com").toString();
|
||||||
|
|
||||||
|
// 从缓存获取问卷模板
|
||||||
|
List<Map<String, Object>> questionTemplate = getQuestionTemplate(productId);
|
||||||
|
|
||||||
|
// 解析出行人问卷答案
|
||||||
|
List<List<CtripDistBookRequest.QuestionAnswer>> passengerAnswers =
|
||||||
|
parsePassengerAnswers(params, questionTemplate);
|
||||||
|
|
||||||
|
// quantity 独立于出行人数量
|
||||||
|
int quantity = params.get("quantity") != null
|
||||||
|
? Integer.parseInt(params.get("quantity").toString())
|
||||||
|
: passengerAnswers.size();
|
||||||
|
|
||||||
|
String useDate = params.getOrDefault("useDate",
|
||||||
|
LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))).toString();
|
||||||
|
|
||||||
|
String distributorOrderId = "TEST_" + System.currentTimeMillis();
|
||||||
|
CtripDistBookRequest request = buildTestBookRequest(
|
||||||
|
distributorOrderId, productId, packageId, resourceId,
|
||||||
|
price, quantity, useDate, contactName, contactMobile, contactEmail,
|
||||||
|
passengerAnswers);
|
||||||
|
|
||||||
|
log.info("下单请求 distributorOrderId: {}, 购买数量: {}, 出行人数: {}",
|
||||||
|
distributorOrderId, quantity, passengerAnswers.size());
|
||||||
|
CtripDistBookResponse response = ctripDistApiService.createOrder(request);
|
||||||
|
log.info("创建订单返回: success={}, orderId={}", response.isSuccess(),
|
||||||
|
response.getData() != null ? response.getData().getOrderId() : "null");
|
||||||
|
return Result.succeed(response, "创建订单调用完成");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("创建携程订单失败", e);
|
||||||
|
return Result.failed("创建携程订单失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试创建携程订单(直接传完整请求体)
|
||||||
|
* 用途:如果需要精确控制所有字段,直接传CtripDistBookRequest JSON
|
||||||
|
*
|
||||||
|
* 调用示例:POST /ctrip/dist/test/book/raw
|
||||||
|
* Body: 完整的CtripDistBookRequest JSON
|
||||||
|
*/
|
||||||
|
@PostMapping("/book/raw")
|
||||||
|
@Operation(summary = "3.创建携程订单(原始请求体)")
|
||||||
|
public Result<CtripDistBookResponse> testCreateOrderRaw(@RequestBody CtripDistBookRequest request) {
|
||||||
|
log.info("===== 测试创建携程订单(raw),distributorOrderID: {} =====", request.getDistributorOrderID());
|
||||||
|
try {
|
||||||
|
CtripDistBookResponse response = ctripDistApiService.createOrder(request);
|
||||||
|
log.info("创建订单返回: success={}", response.isSuccess());
|
||||||
|
return Result.succeed(response, "创建订单调用完成");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("创建携程订单失败", e);
|
||||||
|
return Result.failed("创建携程订单失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 4. 可退检查 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试取消验证(可退检查)
|
||||||
|
* 用途:检查某个携程订单是否可以取消/退订
|
||||||
|
* 需要先通过接口3创建订单获得ctripOrderId
|
||||||
|
*
|
||||||
|
* 调用示例:GET /ctrip/dist/test/cancel-verify?ctripOrderId=123456789
|
||||||
|
*/
|
||||||
|
@GetMapping("/cancel-verify")
|
||||||
|
@Operation(summary = "4.可退检查")
|
||||||
|
public Result<CtripDistCancelVerifyResponse> testCancelVerify(@RequestParam Long ctripOrderId) {
|
||||||
|
log.info("===== 测试取消验证,ctripOrderId: {} =====", ctripOrderId);
|
||||||
|
try {
|
||||||
|
CtripDistCancelVerifyResponse response = ctripDistApiService.cancelVerify(ctripOrderId);
|
||||||
|
log.info("取消验证返回: success={}, cancelVerifyStatus={}",
|
||||||
|
response.isSuccess(),
|
||||||
|
response.getCancelVerifyData() != null
|
||||||
|
? response.getCancelVerifyData().getCancelVerifyStatus() : "null");
|
||||||
|
return Result.succeed(response, "取消验证调用完成");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("取消验证失败,ctripOrderId: {}", ctripOrderId, e);
|
||||||
|
return Result.failed("取消验证失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 5. 退订(全部退订) ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试退订(全部取消订单)
|
||||||
|
* 用途:取消携程订单,需先通过接口4确认可退
|
||||||
|
*
|
||||||
|
* 调用示例:POST /ctrip/dist/test/cancel?ctripOrderId=123456789&reason=测试退订
|
||||||
|
*/
|
||||||
|
@PostMapping("/cancel")
|
||||||
|
@Operation(summary = "5.退订(全部取消订单)")
|
||||||
|
public Result<CtripDistCancelResponse> testCancelOrder(
|
||||||
|
@RequestParam Long ctripOrderId,
|
||||||
|
@RequestParam(defaultValue = "沙箱测试退订") String reason) {
|
||||||
|
log.info("===== 测试全部退订,ctripOrderId: {}, reason: {} =====", ctripOrderId, reason);
|
||||||
|
try {
|
||||||
|
CtripDistCancelResponse response = ctripDistApiService.cancelOrder(ctripOrderId, reason);
|
||||||
|
log.info("退订返回: success={}", response.isSuccess());
|
||||||
|
return Result.succeed(response, "退订调用完成");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("退订失败,ctripOrderId: {}", ctripOrderId, e);
|
||||||
|
return Result.failed("退订失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 5.5 部分退订 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试部分退订
|
||||||
|
* 用途:部分取消携程订单(如购买2张退1张),需先通过接口4确认可部分退
|
||||||
|
*
|
||||||
|
* 调用示例:POST /ctrip/dist/test/cancel-partial
|
||||||
|
* Body:
|
||||||
|
* {
|
||||||
|
* "ctripOrderId": 123456789,
|
||||||
|
* "reason": "沙箱测试部分退订",
|
||||||
|
* "cancelOrderItems": [
|
||||||
|
* {
|
||||||
|
* "itemID": 1001,
|
||||||
|
* "quantity": 1
|
||||||
|
* }
|
||||||
|
* ]
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
@PostMapping("/cancel-partial")
|
||||||
|
@Operation(summary = "5.5 部分退订")
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public Result<CtripDistCancelResponse> testCancelOrderPartial(@RequestBody Map<String, Object> params) {
|
||||||
|
Long ctripOrderId = Long.valueOf(params.get("ctripOrderId").toString());
|
||||||
|
String reason = params.getOrDefault("reason", "沙箱测试部分退订").toString();
|
||||||
|
List<Map<String, Object>> cancelOrderItems = (List<Map<String, Object>>) params.get("cancelOrderItems");
|
||||||
|
log.info("===== 测试部分退订,ctripOrderId: {}, reason: {}, cancelOrderItems: {} =====",
|
||||||
|
ctripOrderId, reason, cancelOrderItems);
|
||||||
|
try {
|
||||||
|
CtripDistCancelResponse response = ctripDistApiService.cancelOrderPartial(ctripOrderId, reason, cancelOrderItems);
|
||||||
|
log.info("部分退订返回: success={}", response.isSuccess());
|
||||||
|
return Result.succeed(response, "部分退订调用完成");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("部分退订失败,ctripOrderId: {}", ctripOrderId, e);
|
||||||
|
return Result.failed("部分退订失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 6. 订单详情 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试查询携程订单详情
|
||||||
|
* 用途:根据携程订单ID查询订单状态和详细信息
|
||||||
|
*
|
||||||
|
* 调用示例:GET /ctrip/dist/test/booking-detail?ctripOrderId=123456789
|
||||||
|
*/
|
||||||
|
@GetMapping("/booking-detail")
|
||||||
|
@Operation(summary = "6.携程订单详情")
|
||||||
|
public Result<CtripDistBookingDetailResponse> testBookingDetail(@RequestParam Long ctripOrderId) {
|
||||||
|
log.info("===== 测试查询订单详情,ctripOrderId: {} =====", ctripOrderId);
|
||||||
|
try {
|
||||||
|
CtripDistBookingDetailResponse response = ctripDistApiService.getOrderDetail(ctripOrderId);
|
||||||
|
log.info("订单详情返回: success={}, orderStatus={}",
|
||||||
|
response.isSuccess(),
|
||||||
|
response.getData() != null && response.getData().getOrder() != null
|
||||||
|
? response.getData().getOrder().getOrderStatus() : "null");
|
||||||
|
return Result.succeed(response, "查询订单详情完成");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("查询订单详情失败,ctripOrderId: {}", ctripOrderId, e);
|
||||||
|
return Result.failed("查询订单详情失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 7. 沙箱-模拟携程发起退订(Part M 11.2) ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 模拟携程侧发起退订
|
||||||
|
* 用途:沙箱测试时模拟携程侧退订(非分销商发起),退订后可调接口6查看订单状态
|
||||||
|
*
|
||||||
|
* 整单退示例:POST /ctrip/dist/test/simulate-cancel
|
||||||
|
* Body: {"orderId": "1128170608930095"}
|
||||||
|
*
|
||||||
|
* 部分退示例(一张一人的订单,传clientId):
|
||||||
|
* Body:
|
||||||
|
* {
|
||||||
|
* "orderId": "1128170612314784",
|
||||||
|
* "quantity": 1,
|
||||||
|
* "clientInfoList": [
|
||||||
|
* {"clientId": "1756725089476701"}
|
||||||
|
* ]
|
||||||
|
* }
|
||||||
|
* 注意:clientId 从订单详情接口(接口6)返回的出行人 P_CLIENTID 获取
|
||||||
|
*/
|
||||||
|
@PostMapping("/simulate-cancel")
|
||||||
|
@Operation(summary = "7.沙箱-模拟携程发起退订")
|
||||||
|
public Result<Map<String, Object>> testSimulateCtripCancel(@RequestBody Map<String, Object> params) {
|
||||||
|
log.info("===== 沙箱-模拟携程发起退订,params: {} =====", params);
|
||||||
|
try {
|
||||||
|
Map<String, Object> response = ctripDistApiService.simulateCtripCancel(params);
|
||||||
|
log.info("模拟携程退订返回: {}", response);
|
||||||
|
return Result.succeed(response, "模拟携程退订调用完成");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("模拟携程退订失败", e);
|
||||||
|
return Result.failed("模拟携程退订失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 8. 沙箱-人工出票/退订确认/退订拒绝/凭证变更(Part M 11.3) ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 沙箱测试-人工出票/退订确认/退订拒绝/凭证变更
|
||||||
|
* 用途:对卡在出票中/退订中的订单进行人工操作
|
||||||
|
*
|
||||||
|
* type说明:
|
||||||
|
* 1 = 人工出票(对卡在出票中或需人工确认的订单)
|
||||||
|
* 2 = 退订确认(对卡在退订中的订单)
|
||||||
|
* 3 = 退订拒绝(模拟携程侧拒绝退订)
|
||||||
|
* 4 = 凭证变更
|
||||||
|
*
|
||||||
|
* 调用示例:POST /ctrip/dist/test/simulate-confirm
|
||||||
|
* Body: {"orderId": "1128170612557359", "type": 1}
|
||||||
|
*/
|
||||||
|
@PostMapping("/simulate-confirm")
|
||||||
|
@Operation(summary = "8.沙箱-人工出票/退订确认/退订拒绝/凭证变更")
|
||||||
|
public Result<Map<String, Object>> testSimulateConfirm(@RequestBody Map<String, Object> params) {
|
||||||
|
Object type = params.get("type");
|
||||||
|
String[] typeNames = {"", "人工出票", "退订确认", "退订拒绝", "凭证变更"};
|
||||||
|
String typeName = type != null && Integer.parseInt(type.toString()) >= 1 && Integer.parseInt(type.toString()) <= 4
|
||||||
|
? typeNames[Integer.parseInt(type.toString())] : "未知类型";
|
||||||
|
log.info("===== 沙箱-{},params: {} =====", typeName, params);
|
||||||
|
try {
|
||||||
|
Map<String, Object> response = ctripDistApiService.simulateConfirm(params);
|
||||||
|
log.info("沙箱-{}返回: {}", typeName, response);
|
||||||
|
return Result.succeed(response, typeName + "调用完成");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("沙箱-{}失败", typeName, e);
|
||||||
|
return Result.failed(typeName + "失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 辅助方法 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从缓存获取产品的问卷模板
|
||||||
|
* 如果未缓存,提示用户先调用接口2
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private List<Map<String, Object>> getQuestionTemplate(Long productId) {
|
||||||
|
Map<String, Object> bookInfo = bookInfoCache.get(productId);
|
||||||
|
if (bookInfo == null) {
|
||||||
|
throw new RuntimeException("productId=" + productId + " 的bookInfo未缓存,请先调用接口2(GET /ctrip/dist/test/book-info)");
|
||||||
|
}
|
||||||
|
return extractQuestionTemplate(bookInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从 bookInfo 响应中提取问卷模板列表
|
||||||
|
* bookInfo 结构: { success: true, data: { passengerQuestionList: [...] } }
|
||||||
|
* 每个问卷项: { questionID: 3, questionCode: "P_NAME", questionTitle: "UserName", ... }
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private List<Map<String, Object>> extractQuestionTemplate(Map<String, Object> bookInfo) {
|
||||||
|
if (bookInfo == null || bookInfo.get("data") == null) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
Map<String, Object> data = (Map<String, Object>) bookInfo.get("data");
|
||||||
|
Object questionList = data.get("passengerQuestionList");
|
||||||
|
if (questionList instanceof List) {
|
||||||
|
return (List<Map<String, Object>>) questionList;
|
||||||
|
}
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析出行人问卷答案
|
||||||
|
*
|
||||||
|
* passengers中每个出行人是一个Map,key为questionCode,value为答案值
|
||||||
|
* 示例: {"P_FIRSTCNAME": "Chao", "P_LASTCNAME": "Du"}
|
||||||
|
*
|
||||||
|
* 系统自动从缓存的问卷模板中匹配questionID和questionTitle
|
||||||
|
*
|
||||||
|
* 如果没有传passengers,则返回空的单个出行人(无问卷答案)
|
||||||
|
*
|
||||||
|
* @param params 请求参数
|
||||||
|
* @param questionTemplate 从bookInfo缓存中获取的问卷模板
|
||||||
|
* @return 每个出行人的问卷答案列表
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private List<List<CtripDistBookRequest.QuestionAnswer>> parsePassengerAnswers(
|
||||||
|
Map<String, Object> params, List<Map<String, Object>> questionTemplate) {
|
||||||
|
|
||||||
|
List<List<CtripDistBookRequest.QuestionAnswer>> result = new ArrayList<>();
|
||||||
|
Object passengersObj = params.get("passengers");
|
||||||
|
|
||||||
|
if (passengersObj instanceof List) {
|
||||||
|
List<Map<String, Object>> passengers = (List<Map<String, Object>>) passengersObj;
|
||||||
|
// 构建 questionCode → 模板 的映射
|
||||||
|
// 携程返回的字段名是 "code"(不是 "questionCode")
|
||||||
|
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) {
|
||||||
|
List<CtripDistBookRequest.QuestionAnswer> answers = new ArrayList<>();
|
||||||
|
for (Map.Entry<String, Object> entry : passengerMap.entrySet()) {
|
||||||
|
String questionCode = entry.getKey();
|
||||||
|
String answerValue = entry.getValue() != null ? entry.getValue().toString() : "";
|
||||||
|
|
||||||
|
// 从模板匹配 questionID 和 questionTitle
|
||||||
|
Map<String, Object> template = templateMap.get(questionCode);
|
||||||
|
if (template != null) {
|
||||||
|
CtripDistBookRequest.QuestionAnswer answer = new CtripDistBookRequest.QuestionAnswer();
|
||||||
|
answer.setQuestionID(Long.valueOf(template.get("questionID").toString()));
|
||||||
|
answer.setQuestionCode(questionCode);
|
||||||
|
String title = getFieldValue(template, "title", "questionTitle");
|
||||||
|
answer.setQuestionTitle(title != null ? title : "");
|
||||||
|
answer.setAnswerList(Collections.singletonList(answerValue));
|
||||||
|
answers.add(answer);
|
||||||
|
} else {
|
||||||
|
log.warn("questionCode={} 在问卷模板中未找到,跳过", questionCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result.add(answers);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.isEmpty()) {
|
||||||
|
// 没有传passengers,返回一个无答案的出行人
|
||||||
|
result.add(new ArrayList<>());
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建测试下单请求(通用版)
|
||||||
|
*
|
||||||
|
* @param passengerAnswers 每个出行人的问卷答案(从parsePassengerAnswers得到)
|
||||||
|
* @param quantity 购买数量(与出行人数量解耦)
|
||||||
|
* @param useDate 使用日期
|
||||||
|
*/
|
||||||
|
private CtripDistBookRequest buildTestBookRequest(String distributorOrderId, Long productId,
|
||||||
|
Long packageId, Long resourceId,
|
||||||
|
BigDecimal price, int quantity,
|
||||||
|
String useDate,
|
||||||
|
String contactName, String contactMobile,
|
||||||
|
String contactEmail,
|
||||||
|
List<List<CtripDistBookRequest.QuestionAnswer>> passengerAnswers) {
|
||||||
|
CtripDistBookRequest request = new CtripDistBookRequest();
|
||||||
|
request.setLocale("zh-CN");
|
||||||
|
request.setCurrency("CNY");
|
||||||
|
request.setDistributorOrderID(distributorOrderId);
|
||||||
|
|
||||||
|
// 联系人
|
||||||
|
CtripDistBookRequest.Contact contact = new CtripDistBookRequest.Contact();
|
||||||
|
contact.setName(contactName);
|
||||||
|
CtripDistBookRequest.Mobile mobile = new CtripDistBookRequest.Mobile();
|
||||||
|
mobile.setInternationalTelephoneCode("86");
|
||||||
|
mobile.setMobileNumber(contactMobile);
|
||||||
|
contact.setMobile(mobile);
|
||||||
|
contact.setEmail(contactEmail);
|
||||||
|
request.setContact(contact);
|
||||||
|
|
||||||
|
// 为每个出行人构建Passenger对象
|
||||||
|
List<CtripDistBookRequest.Passenger> passengerList = new ArrayList<>();
|
||||||
|
for (List<CtripDistBookRequest.QuestionAnswer> answers : passengerAnswers) {
|
||||||
|
CtripDistBookRequest.Passenger passenger = new CtripDistBookRequest.Passenger();
|
||||||
|
passenger.setPackageID(packageId);
|
||||||
|
passenger.setResourceID(resourceId);
|
||||||
|
passenger.setQuestionAnswerList(answers);
|
||||||
|
passengerList.add(passenger);
|
||||||
|
}
|
||||||
|
request.setPassengerList(passengerList);
|
||||||
|
|
||||||
|
// 订单资源
|
||||||
|
CtripDistBookRequest.OrderResource orderResource = new CtripDistBookRequest.OrderResource();
|
||||||
|
orderResource.setResourceID(resourceId);
|
||||||
|
orderResource.setUseDate(useDate);
|
||||||
|
orderResource.setQuantity(quantity);
|
||||||
|
orderResource.setPrice(price);
|
||||||
|
|
||||||
|
// 基本订单信息
|
||||||
|
BigDecimal totalAmount = price.multiply(new BigDecimal(quantity));
|
||||||
|
CtripDistBookRequest.BasicOrder basicOrder = new CtripDistBookRequest.BasicOrder();
|
||||||
|
basicOrder.setProductID(productId);
|
||||||
|
basicOrder.setAmount(totalAmount);
|
||||||
|
basicOrder.setPackageID(packageId);
|
||||||
|
basicOrder.setOrderResourceList(Collections.singletonList(orderResource));
|
||||||
|
request.setBasicOrder(basicOrder);
|
||||||
|
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从Map中按优先级获取字段值
|
||||||
|
* 携程接口返回的字段名可能与文档不一致(如 "code" vs "questionCode","title" vs "questionTitle")
|
||||||
|
*/
|
||||||
|
private String getFieldValue(Map<String, Object> map, String... keys) {
|
||||||
|
for (String key : keys) {
|
||||||
|
Object val = map.get(key);
|
||||||
|
if (val != null) {
|
||||||
|
return val.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
+83
@@ -0,0 +1,83 @@
|
|||||||
|
package com.central.coupon.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = false)
|
||||||
|
@TableName("t_ctrip_dist_order")
|
||||||
|
public class CtripDistOrder {
|
||||||
|
|
||||||
|
@TableId(value = "id", type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
@TableField("tenant_id")
|
||||||
|
private String tenantId;
|
||||||
|
|
||||||
|
@TableField("order_no")
|
||||||
|
private String orderNo;
|
||||||
|
|
||||||
|
@TableField("ctrip_order_id")
|
||||||
|
private Long ctripOrderId;
|
||||||
|
|
||||||
|
@TableField("ctrip_product_id")
|
||||||
|
private Long ctripProductId;
|
||||||
|
|
||||||
|
@TableField("ctrip_package_id")
|
||||||
|
private Long ctripPackageId;
|
||||||
|
|
||||||
|
@TableField("ctrip_resource_id")
|
||||||
|
private Long ctripResourceId;
|
||||||
|
|
||||||
|
@TableField("distributor_order_id")
|
||||||
|
private String distributorOrderId;
|
||||||
|
|
||||||
|
@TableField("order_amount")
|
||||||
|
private BigDecimal orderAmount;
|
||||||
|
|
||||||
|
@TableField("currency")
|
||||||
|
private String currency;
|
||||||
|
|
||||||
|
@TableField("ctrip_order_status")
|
||||||
|
private String ctripOrderStatus;
|
||||||
|
|
||||||
|
@TableField("consume_status")
|
||||||
|
private Integer consumeStatus;
|
||||||
|
|
||||||
|
@TableField("consume_time")
|
||||||
|
private LocalDateTime consumeTime;
|
||||||
|
|
||||||
|
@TableField("refund_status")
|
||||||
|
private Integer refundStatus;
|
||||||
|
|
||||||
|
@TableField("refund_time")
|
||||||
|
private LocalDateTime refundTime;
|
||||||
|
|
||||||
|
@TableField("refund_amount")
|
||||||
|
private BigDecimal refundAmount;
|
||||||
|
|
||||||
|
@TableField("error_msg")
|
||||||
|
private String errorMsg;
|
||||||
|
|
||||||
|
@TableField("retry_count")
|
||||||
|
private Integer retryCount;
|
||||||
|
|
||||||
|
@TableField("remark")
|
||||||
|
private String remark;
|
||||||
|
|
||||||
|
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
|
||||||
|
@TableField("deleted")
|
||||||
|
private Integer deleted;
|
||||||
|
}
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
package com.central.coupon.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.central.coupon.entity.CtripDistOrder;
|
||||||
|
import java.util.List;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public interface CtripDistOrderMapper extends BaseMapper<CtripDistOrder> {
|
||||||
|
|
||||||
|
// 根据本地订单号查询
|
||||||
|
CtripDistOrder selectByOrderNo(@Param("orderNo") String orderNo);
|
||||||
|
|
||||||
|
// 查询 N 天前创建、已确认且未核销的订单
|
||||||
|
List<CtripDistOrder> selectPendingConsumeOrders(@Param("daysAgo") int daysAgo);
|
||||||
|
|
||||||
|
// 根据分销商订单 ID 查询
|
||||||
|
CtripDistOrder selectByDistributorOrderId(@Param("distributorOrderId") String distributorOrderId);
|
||||||
|
}
|
||||||
+68
@@ -0,0 +1,68 @@
|
|||||||
|
package com.central.coupon.model;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.List;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public class CtripDistBookRequest {
|
||||||
|
|
||||||
|
private String locale;
|
||||||
|
private String currency;
|
||||||
|
private String distributorOrderID;
|
||||||
|
private Contact contact;
|
||||||
|
private List<Passenger> passengerList;
|
||||||
|
private BasicOrder basicOrder;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public static class Contact {
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
private Mobile mobile;
|
||||||
|
private String email;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public static class Mobile {
|
||||||
|
|
||||||
|
private String internationalTelephoneCode;
|
||||||
|
private String mobileNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public static class Passenger {
|
||||||
|
|
||||||
|
private Long packageID;
|
||||||
|
private Long resourceID;
|
||||||
|
private List<QuestionAnswer> questionAnswerList;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public static class QuestionAnswer {
|
||||||
|
|
||||||
|
private Long questionID;
|
||||||
|
private String questionCode;
|
||||||
|
private String questionTitle;
|
||||||
|
private List<String> answerList;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public static class BasicOrder {
|
||||||
|
|
||||||
|
private Long productID;
|
||||||
|
private BigDecimal amount;
|
||||||
|
private Long packageID;
|
||||||
|
private List<OrderResource> orderResourceList;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public static class OrderResource {
|
||||||
|
|
||||||
|
private Long resourceID;
|
||||||
|
private String useDate;
|
||||||
|
private Integer quantity;
|
||||||
|
private BigDecimal price;
|
||||||
|
}
|
||||||
|
}
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
package com.central.coupon.model;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public class CtripDistBookResponse {
|
||||||
|
|
||||||
|
private boolean success;
|
||||||
|
private String errcode;
|
||||||
|
private String errmsg;
|
||||||
|
private BookData data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public static class BookData {
|
||||||
|
|
||||||
|
private Long orderId;
|
||||||
|
private BigDecimal orderAmount;
|
||||||
|
private Integer payTimeOutMinutes;
|
||||||
|
}
|
||||||
|
}
|
||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
package com.central.coupon.model;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public class CtripDistBookingDetailResponse {
|
||||||
|
|
||||||
|
private boolean success;
|
||||||
|
private String errcode;
|
||||||
|
private String errmsg;
|
||||||
|
private OrderData data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public static class OrderData {
|
||||||
|
|
||||||
|
private OrderDetail order;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public static class OrderDetail {
|
||||||
|
|
||||||
|
private Long orderId;
|
||||||
|
// PENDING_BOOKING, CONFIRMED, CANCELLED, etc.
|
||||||
|
private String orderStatus;
|
||||||
|
private BigDecimal amount;
|
||||||
|
private String distributorOrderID;
|
||||||
|
}
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
package com.central.coupon.model;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public class CtripDistCancelResponse {
|
||||||
|
|
||||||
|
private boolean success;
|
||||||
|
private String errcode;
|
||||||
|
private String errmsg;
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
package com.central.coupon.model;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public class CtripDistCancelVerifyResponse {
|
||||||
|
|
||||||
|
private boolean success;
|
||||||
|
private String errcode;
|
||||||
|
private String errmsg;
|
||||||
|
private CancelVerifyData cancelVerifyData;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public static class CancelVerifyData {
|
||||||
|
|
||||||
|
// 0=不可取消, 1=可取消, 3=部分退订
|
||||||
|
private Integer cancelVerifyStatus;
|
||||||
|
private BigDecimal refundAmount;
|
||||||
|
// 1=允许部分退, 2=不允许
|
||||||
|
private Integer canPartRefund;
|
||||||
|
}
|
||||||
|
}
|
||||||
+101
@@ -0,0 +1,101 @@
|
|||||||
|
package com.central.coupon.service;
|
||||||
|
|
||||||
|
import com.central.coupon.model.CtripDistBookRequest;
|
||||||
|
import com.central.coupon.model.CtripDistBookResponse;
|
||||||
|
import com.central.coupon.model.CtripDistBookingDetailResponse;
|
||||||
|
import com.central.coupon.model.CtripDistCancelResponse;
|
||||||
|
import com.central.coupon.model.CtripDistCancelVerifyResponse;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程分销商API服务
|
||||||
|
*/
|
||||||
|
public interface ICtripDistApiService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询产品详情
|
||||||
|
*
|
||||||
|
* @param productId 产品ID
|
||||||
|
* @return 产品详情
|
||||||
|
*/
|
||||||
|
Map<String, Object> getProductDetail(Long productId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取下单填写信息
|
||||||
|
*
|
||||||
|
* @param productId 产品ID
|
||||||
|
* @param packageId 套餐ID
|
||||||
|
* @param resourceId 资源ID
|
||||||
|
* @return 下单填写信息
|
||||||
|
*/
|
||||||
|
Map<String, Object> getBookInfo(Long productId, Long packageId, Long resourceId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建订单
|
||||||
|
*
|
||||||
|
* @param request 下单请求
|
||||||
|
* @return 下单响应
|
||||||
|
*/
|
||||||
|
CtripDistBookResponse createOrder(CtripDistBookRequest request);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消验证
|
||||||
|
*
|
||||||
|
* @param ctripOrderId 携程订单ID
|
||||||
|
* @return 取消验证结果
|
||||||
|
*/
|
||||||
|
CtripDistCancelVerifyResponse cancelVerify(Long ctripOrderId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消订单(全部退订)
|
||||||
|
*
|
||||||
|
* @param ctripOrderId 携程订单ID
|
||||||
|
* @param reason 取消原因
|
||||||
|
* @return 取消结果
|
||||||
|
*/
|
||||||
|
CtripDistCancelResponse cancelOrder(Long ctripOrderId, String reason);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 部分退订
|
||||||
|
*
|
||||||
|
* @param ctripOrderId 携程订单ID
|
||||||
|
* @param reason 取消原因
|
||||||
|
* @param cancelOrderItems 部分取消的订单项列表
|
||||||
|
* @return 取消结果
|
||||||
|
*/
|
||||||
|
CtripDistCancelResponse cancelOrderPartial(Long ctripOrderId, String reason, List<Map<String, Object>> cancelOrderItems);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询订单详情
|
||||||
|
*
|
||||||
|
* @param ctripOrderId 携程订单ID
|
||||||
|
* @return 订单详情
|
||||||
|
*/
|
||||||
|
CtripDistBookingDetailResponse getOrderDetail(Long ctripOrderId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 可订检查(下单前调用,确认资源可预订)
|
||||||
|
* 请求参数与下单接口一致
|
||||||
|
*
|
||||||
|
* @param request 下单请求(与book接口相同)
|
||||||
|
* @return 是否可订
|
||||||
|
*/
|
||||||
|
boolean checkAvailability(CtripDistBookRequest request);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 沙箱测试-模拟携程发起退订(Part M 11.2)
|
||||||
|
*
|
||||||
|
* @param requestBody 请求体(orderId必填,部分退时含quantity和clientInfoList)
|
||||||
|
* @return 响应
|
||||||
|
*/
|
||||||
|
Map<String, Object> simulateCtripCancel(Map<String, Object> requestBody);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 沙箱测试-人工出票/退订确认/退订拒绝/凭证变更(Part M 11.3)
|
||||||
|
*
|
||||||
|
* @param requestBody 请求体(orderId + type: 1=人工出票, 2=退订确认, 3=退订拒绝, 4=凭证变更)
|
||||||
|
* @return 响应
|
||||||
|
*/
|
||||||
|
Map<String, Object> simulateConfirm(Map<String, Object> requestBody);
|
||||||
|
}
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
package com.central.coupon.service;
|
||||||
|
|
||||||
|
import com.central.coupon.entity.CtripDistOrder;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程分销商订单服务
|
||||||
|
*/
|
||||||
|
public interface ICtripDistOrderService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建携程分销商订单
|
||||||
|
*
|
||||||
|
* @param orderNo 本地订单号
|
||||||
|
* @param orderAmount 订单金额,单位分
|
||||||
|
* @param ctripProductId 携程产品ID
|
||||||
|
* @param tenantId 租户ID
|
||||||
|
* @param mobile 用户手机号(可为null,为null时使用默认值)
|
||||||
|
*/
|
||||||
|
void createCtripDistOrder(String orderNo, String orderAmount, Long ctripProductId, String tenantId, String mobile);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消携程分销商订单
|
||||||
|
*
|
||||||
|
* @param orderNo 本地订单号
|
||||||
|
* @param reason 取消原因
|
||||||
|
* @return 是否取消成功
|
||||||
|
*/
|
||||||
|
boolean cancelCtripDistOrder(String orderNo, String reason);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据订单号查询订单
|
||||||
|
*
|
||||||
|
* @param orderNo 本地订单号
|
||||||
|
* @return 分销商订单
|
||||||
|
*/
|
||||||
|
CtripDistOrder getByOrderNo(String orderNo);
|
||||||
|
}
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package com.central.coupon.service;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程分销商Token管理服务
|
||||||
|
*/
|
||||||
|
public interface ICtripDistTokenService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取有效的AccessToken(自动刷新)
|
||||||
|
*
|
||||||
|
* @return 有效的AccessToken
|
||||||
|
*/
|
||||||
|
String getAccessToken();
|
||||||
|
}
|
||||||
+154
@@ -0,0 +1,154 @@
|
|||||||
|
package com.central.coupon.service.impl;
|
||||||
|
|
||||||
|
import com.central.common.utils.http.SimpleHttpRequest;
|
||||||
|
import com.central.coupon.config.CtripDistributorConfig;
|
||||||
|
import com.central.coupon.model.CtripDistBookRequest;
|
||||||
|
import com.central.coupon.model.CtripDistBookResponse;
|
||||||
|
import com.central.coupon.model.CtripDistBookingDetailResponse;
|
||||||
|
import com.central.coupon.model.CtripDistCancelResponse;
|
||||||
|
import com.central.coupon.model.CtripDistCancelVerifyResponse;
|
||||||
|
import com.central.coupon.service.ICtripDistApiService;
|
||||||
|
import com.central.coupon.service.ICtripDistTokenService;
|
||||||
|
import com.central.coupon.util.SslUtil;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程分销商API服务实现
|
||||||
|
* 使用SimpleHttpRequest替代RestTemplate,解决HTTPS连接兼容性问题
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class CtripDistApiServiceImpl implements ICtripDistApiService {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CtripDistributorConfig config;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ICtripDistTokenService tokenService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, Object> getProductDetail(Long productId) {
|
||||||
|
Map<String, Object> requestBody = new HashMap<>();
|
||||||
|
requestBody.put("locale", config.getLocale());
|
||||||
|
requestBody.put("currency", config.getCurrency());
|
||||||
|
requestBody.put("productIDList", Collections.singletonList(productId));
|
||||||
|
return callApi(config.getIcode().getProductDetail(), requestBody, Map.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, Object> getBookInfo(Long productId, Long packageId, Long resourceId) {
|
||||||
|
Map<String, Object> requestBody = new HashMap<>();
|
||||||
|
requestBody.put("locale", config.getLocale());
|
||||||
|
requestBody.put("currency", config.getCurrency());
|
||||||
|
requestBody.put("productID", productId);
|
||||||
|
requestBody.put("packageID", packageId);
|
||||||
|
requestBody.put("resourceID", resourceId);
|
||||||
|
return callApi(config.getIcode().getBookInfo(), requestBody, Map.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CtripDistBookResponse createOrder(CtripDistBookRequest request) {
|
||||||
|
return callApi(config.getIcode().getBook(), request, CtripDistBookResponse.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CtripDistCancelVerifyResponse cancelVerify(Long ctripOrderId) {
|
||||||
|
Map<String, Object> requestBody = new HashMap<>();
|
||||||
|
requestBody.put("orderId", ctripOrderId);
|
||||||
|
requestBody.put("locale", config.getLocale());
|
||||||
|
return callApi(config.getIcode().getCancelVerify(), requestBody, CtripDistCancelVerifyResponse.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CtripDistCancelResponse cancelOrder(Long ctripOrderId, String reason) {
|
||||||
|
Map<String, Object> requestBody = new HashMap<>();
|
||||||
|
requestBody.put("orderId", ctripOrderId);
|
||||||
|
requestBody.put("reason", reason);
|
||||||
|
return callApi(config.getIcode().getCancel(), requestBody, CtripDistCancelResponse.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CtripDistCancelResponse cancelOrderPartial(Long ctripOrderId, String reason, java.util.List<Map<String, Object>> cancelOrderItems) {
|
||||||
|
Map<String, Object> requestBody = new HashMap<>();
|
||||||
|
requestBody.put("orderId", ctripOrderId);
|
||||||
|
requestBody.put("reason", reason);
|
||||||
|
requestBody.put("cancelOrderItems", cancelOrderItems);
|
||||||
|
return callApi(config.getIcode().getCancel(), requestBody, CtripDistCancelResponse.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CtripDistBookingDetailResponse getOrderDetail(Long ctripOrderId) {
|
||||||
|
Map<String, Object> requestBody = new HashMap<>();
|
||||||
|
requestBody.put("orderID", ctripOrderId);
|
||||||
|
return callApi(config.getIcode().getBookingDetail(), requestBody, CtripDistBookingDetailResponse.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
@Override
|
||||||
|
public boolean checkAvailability(CtripDistBookRequest request) {
|
||||||
|
Map<String, Object> response = callApi(config.getIcode().getCheckAvailability(), request, Map.class);
|
||||||
|
log.info("可订检查完整响应: {}", response);
|
||||||
|
Object success = response.get("success");
|
||||||
|
if (success == null || !Boolean.parseBoolean(success.toString())) {
|
||||||
|
log.warn("可订检查失败, success={}, errcode={}, errmsg={}",
|
||||||
|
success, response.get("errcode"), response.get("errmsg"));
|
||||||
|
}
|
||||||
|
return success != null && Boolean.parseBoolean(success.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, Object> simulateCtripCancel(Map<String, Object> requestBody) {
|
||||||
|
return callApi(config.getIcode().getSimulateCancel(), requestBody, Map.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, Object> simulateConfirm(Map<String, Object> requestBody) {
|
||||||
|
return callApi(config.getIcode().getSimulateConfirm(), requestBody, Map.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> T callApi(String icode, Object requestBody, Class<T> responseType) {
|
||||||
|
String token = tokenService.getAccessToken();
|
||||||
|
String uuid = UUID.randomUUID().toString().replace("-", "");
|
||||||
|
String url = String.format("%s?aid=%s&sid=%s&icode=%s&uuid=%s&token=%s",
|
||||||
|
config.getApiUrl(), config.getAid(), config.getSid(), icode, uuid, token);
|
||||||
|
|
||||||
|
String requestJson;
|
||||||
|
try {
|
||||||
|
requestJson = objectMapper.writeValueAsString(requestBody);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("请求体序列化失败: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("调用携程分销商接口,icode: {}, uuid: {}, requestBody: {}", icode, uuid, requestJson);
|
||||||
|
|
||||||
|
String responseBody;
|
||||||
|
try {
|
||||||
|
SimpleHttpRequest request = new SimpleHttpRequest(url, SslUtil.createTrustAllHttpClient());
|
||||||
|
request.requestBody(requestJson);
|
||||||
|
byte[] bytes = request.post().asBytes();
|
||||||
|
request.close();
|
||||||
|
responseBody = new String(bytes, "UTF-8");
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("携程分销商接口HTTP请求失败: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("携程分销商接口响应,icode: {}, response: {}", icode, responseBody);
|
||||||
|
|
||||||
|
try {
|
||||||
|
return objectMapper.readValue(responseBody, responseType);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("携程分销商接口响应反序列化失败: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+246
@@ -0,0 +1,246 @@
|
|||||||
|
package com.central.coupon.service.impl;
|
||||||
|
|
||||||
|
import com.central.coupon.config.CtripDistributorConfig;
|
||||||
|
import com.central.coupon.entity.CtripDistOrder;
|
||||||
|
import com.central.coupon.mapper.CtripDistOrderMapper;
|
||||||
|
import com.central.coupon.model.CtripDistBookRequest;
|
||||||
|
import com.central.coupon.model.CtripDistBookResponse;
|
||||||
|
import com.central.coupon.model.CtripDistCancelResponse;
|
||||||
|
import com.central.coupon.model.CtripDistCancelVerifyResponse;
|
||||||
|
import com.central.coupon.service.ICtripDistApiService;
|
||||||
|
import com.central.coupon.service.ICtripDistOrderService;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程分销商订单服务实现
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
|
||||||
|
|
||||||
|
private static final DateTimeFormatter USE_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ICtripDistApiService ctripDistApiService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CtripDistOrderMapper ctripDistOrderMapper;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CtripDistributorConfig config;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void createCtripDistOrder(String orderNo, String orderAmount, Long ctripProductId, String tenantId, String mobile) {
|
||||||
|
CtripDistOrder existingOrder = ctripDistOrderMapper.selectByOrderNo(orderNo);
|
||||||
|
if (existingOrder != null) {
|
||||||
|
log.info("携程分销商订单已存在,orderNo: {}", orderNo);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> productDetail = ctripDistApiService.getProductDetail(ctripProductId);
|
||||||
|
Long packageId = extractPackageId(productDetail);
|
||||||
|
Long resourceId = extractResourceId(productDetail);
|
||||||
|
Map<String, Object> bookInfo = ctripDistApiService.getBookInfo(ctripProductId, packageId, resourceId);
|
||||||
|
log.info("携程分销商下单填写信息,orderNo: {}, bookInfo: {}", orderNo, bookInfo);
|
||||||
|
|
||||||
|
// 校验产品是否要求额外乘客问卷(如身份证等),如果要求则无法自动下单
|
||||||
|
validateBookInfo(bookInfo, orderNo);
|
||||||
|
|
||||||
|
String distributorOrderId = orderNo;
|
||||||
|
BigDecimal amountYuan = new BigDecimal(orderAmount).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
|
||||||
|
CtripDistBookRequest request = buildBookRequest(distributorOrderId, ctripProductId, packageId, resourceId, amountYuan, mobile);
|
||||||
|
|
||||||
|
// 可订检查:下单前确认资源可预订
|
||||||
|
boolean available = ctripDistApiService.checkAvailability(request);
|
||||||
|
if (!available) {
|
||||||
|
throw new RuntimeException("携程可订检查失败,资源不可预订,orderNo: " + orderNo);
|
||||||
|
}
|
||||||
|
log.info("携程可订检查通过,orderNo: {}", orderNo);
|
||||||
|
|
||||||
|
CtripDistOrder order = new CtripDistOrder();
|
||||||
|
order.setTenantId(tenantId);
|
||||||
|
order.setOrderNo(orderNo);
|
||||||
|
order.setCtripProductId(ctripProductId);
|
||||||
|
order.setCtripPackageId(packageId);
|
||||||
|
order.setCtripResourceId(resourceId);
|
||||||
|
order.setDistributorOrderId(distributorOrderId);
|
||||||
|
order.setOrderAmount(amountYuan);
|
||||||
|
order.setCurrency(config.getCurrency());
|
||||||
|
order.setCtripOrderStatus("CREATING");
|
||||||
|
order.setConsumeStatus(0);
|
||||||
|
order.setRefundStatus(0);
|
||||||
|
order.setRetryCount(0);
|
||||||
|
order.setDeleted(0);
|
||||||
|
ctripDistOrderMapper.insert(order);
|
||||||
|
|
||||||
|
try {
|
||||||
|
CtripDistBookResponse response = ctripDistApiService.createOrder(request);
|
||||||
|
if (response != null && response.isSuccess() && response.getData() != null && response.getData().getOrderId() != null) {
|
||||||
|
order.setCtripOrderId(response.getData().getOrderId());
|
||||||
|
order.setCtripOrderStatus("CONFIRMED");
|
||||||
|
order.setErrorMsg(null);
|
||||||
|
} else {
|
||||||
|
order.setCtripOrderStatus("CREATE_FAILED");
|
||||||
|
order.setErrorMsg(response == null ? "携程分销商下单返回为空" : response.getErrmsg());
|
||||||
|
}
|
||||||
|
ctripDistOrderMapper.updateById(order);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("创建携程分销商订单异常,orderNo: {}", orderNo, e);
|
||||||
|
order.setCtripOrderStatus("CREATE_FAILED");
|
||||||
|
order.setErrorMsg(e.getMessage());
|
||||||
|
order.setRetryCount(order.getRetryCount() == null ? 1 : order.getRetryCount() + 1);
|
||||||
|
ctripDistOrderMapper.updateById(order);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public boolean cancelCtripDistOrder(String orderNo, String reason) {
|
||||||
|
CtripDistOrder order = ctripDistOrderMapper.selectByOrderNo(orderNo);
|
||||||
|
if (order == null) {
|
||||||
|
log.warn("未找到携程分销商订单,orderNo: {}", orderNo);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (Integer.valueOf(1).equals(order.getConsumeStatus())) {
|
||||||
|
log.warn("订单已核销不可退,orderNo: {}", orderNo);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
CtripDistCancelVerifyResponse verifyResponse = ctripDistApiService.cancelVerify(order.getCtripOrderId());
|
||||||
|
if (verifyResponse == null || verifyResponse.getCancelVerifyData() == null
|
||||||
|
|| verifyResponse.getCancelVerifyData().getCancelVerifyStatus() == null
|
||||||
|
|| verifyResponse.getCancelVerifyData().getCancelVerifyStatus() == 0) {
|
||||||
|
order.setRefundStatus(2);
|
||||||
|
order.setErrorMsg(verifyResponse == null ? "退订验证失败" : verifyResponse.getErrmsg());
|
||||||
|
ctripDistOrderMapper.updateById(order);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
CtripDistCancelResponse cancelResponse = ctripDistApiService.cancelOrder(order.getCtripOrderId(), reason);
|
||||||
|
if (cancelResponse != null && cancelResponse.isSuccess()) {
|
||||||
|
order.setCtripOrderStatus("CANCELLED");
|
||||||
|
order.setRefundStatus(1);
|
||||||
|
order.setRefundTime(LocalDateTime.now());
|
||||||
|
order.setRefundAmount(verifyResponse.getCancelVerifyData().getRefundAmount());
|
||||||
|
order.setErrorMsg(null);
|
||||||
|
ctripDistOrderMapper.updateById(order);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
order.setRefundStatus(2);
|
||||||
|
order.setErrorMsg(cancelResponse == null ? "携程分销商取消订单失败" : cancelResponse.getErrmsg());
|
||||||
|
ctripDistOrderMapper.updateById(order);
|
||||||
|
return false;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("取消携程分销商订单异常,orderNo: {}", orderNo, e);
|
||||||
|
order.setRefundStatus(2);
|
||||||
|
order.setErrorMsg(e.getMessage());
|
||||||
|
ctripDistOrderMapper.updateById(order);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CtripDistOrder getByOrderNo(String orderNo) {
|
||||||
|
return ctripDistOrderMapper.selectByOrderNo(orderNo);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final String DEFAULT_CONTACT_NAME = "杜超";
|
||||||
|
private static final String DEFAULT_CONTACT_MOBILE = "18222892722";
|
||||||
|
private static final String DEFAULT_CONTACT_EMAIL = "1098974448@qq.com";
|
||||||
|
|
||||||
|
private CtripDistBookRequest buildBookRequest(String distributorOrderId, Long productId, Long packageId,
|
||||||
|
Long resourceId, BigDecimal amountYuan, String userMobile) {
|
||||||
|
CtripDistBookRequest request = new CtripDistBookRequest();
|
||||||
|
request.setLocale(config.getLocale());
|
||||||
|
request.setCurrency(config.getCurrency());
|
||||||
|
request.setDistributorOrderID(distributorOrderId);
|
||||||
|
|
||||||
|
// 联系人:优先使用真实手机号,没有则用默认值
|
||||||
|
String contactMobile = (userMobile != null && !userMobile.isEmpty()) ? userMobile : DEFAULT_CONTACT_MOBILE;
|
||||||
|
CtripDistBookRequest.Contact contact = new CtripDistBookRequest.Contact();
|
||||||
|
contact.setName(DEFAULT_CONTACT_NAME);
|
||||||
|
CtripDistBookRequest.Mobile mobile = new CtripDistBookRequest.Mobile();
|
||||||
|
mobile.setInternationalTelephoneCode("86");
|
||||||
|
mobile.setMobileNumber(contactMobile);
|
||||||
|
contact.setMobile(mobile);
|
||||||
|
contact.setEmail(DEFAULT_CONTACT_EMAIL);
|
||||||
|
request.setContact(contact);
|
||||||
|
|
||||||
|
CtripDistBookRequest.Passenger passenger = new CtripDistBookRequest.Passenger();
|
||||||
|
passenger.setPackageID(packageId);
|
||||||
|
passenger.setResourceID(resourceId);
|
||||||
|
passenger.setQuestionAnswerList(new ArrayList<>());
|
||||||
|
request.setPassengerList(Collections.singletonList(passenger));
|
||||||
|
|
||||||
|
CtripDistBookRequest.OrderResource orderResource = new CtripDistBookRequest.OrderResource();
|
||||||
|
orderResource.setResourceID(resourceId);
|
||||||
|
orderResource.setUseDate(LocalDate.now().format(USE_DATE_FORMATTER));
|
||||||
|
orderResource.setQuantity(1);
|
||||||
|
orderResource.setPrice(amountYuan);
|
||||||
|
|
||||||
|
CtripDistBookRequest.BasicOrder basicOrder = new CtripDistBookRequest.BasicOrder();
|
||||||
|
basicOrder.setProductID(productId);
|
||||||
|
basicOrder.setAmount(amountYuan);
|
||||||
|
basicOrder.setPackageID(packageId);
|
||||||
|
basicOrder.setOrderResourceList(Collections.singletonList(orderResource));
|
||||||
|
request.setBasicOrder(basicOrder);
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Long extractPackageId(Map<String, Object> productDetail) {
|
||||||
|
Map<String, Object> data = (Map<String, Object>) productDetail.get("data");
|
||||||
|
List<Map<String, Object>> productList = (List<Map<String, Object>>) data.get("productList");
|
||||||
|
Map<String, Object> product = productList.get(0);
|
||||||
|
List<Map<String, Object>> packageList = (List<Map<String, Object>>) product.get("packageList");
|
||||||
|
Map<String, Object> pkg = packageList.get(0);
|
||||||
|
return Long.valueOf(pkg.get("packageID").toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Long extractResourceId(Map<String, Object> productDetail) {
|
||||||
|
Map<String, Object> data = (Map<String, Object>) productDetail.get("data");
|
||||||
|
List<Map<String, Object>> productList = (List<Map<String, Object>>) data.get("productList");
|
||||||
|
Map<String, Object> product = productList.get(0);
|
||||||
|
List<Map<String, Object>> packageList = (List<Map<String, Object>>) product.get("packageList");
|
||||||
|
Map<String, Object> pkg = packageList.get(0);
|
||||||
|
List<Map<String, Object>> resourceList = (List<Map<String, Object>>) pkg.get("resourceList");
|
||||||
|
Map<String, Object> resource = resourceList.get(0);
|
||||||
|
return Long.valueOf(resource.get("resourceID").toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验下单填写信息
|
||||||
|
* 如果产品要求额外乘客问卷(如身份证等),当前平台无法提供,拒绝自动下单
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private void validateBookInfo(Map<String, Object> bookInfo, String orderNo) {
|
||||||
|
if (bookInfo == null || bookInfo.get("data") == null) {
|
||||||
|
log.warn("获取下单填写信息为空,orderNo: {},继续尝试下单", orderNo);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Map<String, Object> data = (Map<String, Object>) bookInfo.get("data");
|
||||||
|
Object questionList = data.get("passengerQuestionList");
|
||||||
|
if (questionList instanceof List) {
|
||||||
|
List<?> questions = (List<?>) questionList;
|
||||||
|
if (!questions.isEmpty()) {
|
||||||
|
throw new RuntimeException("该携程产品要求填写额外乘客信息(如身份证等),无法自动下单,orderNo: " + orderNo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+127
@@ -0,0 +1,127 @@
|
|||||||
|
package com.central.coupon.service.impl;
|
||||||
|
|
||||||
|
import com.central.common.utils.http.SimpleHttpRequest;
|
||||||
|
import com.central.coupon.config.CtripDistributorConfig;
|
||||||
|
import com.central.coupon.service.ICtripDistTokenService;
|
||||||
|
import com.central.coupon.util.SslUtil;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程分销商Token管理服务实现
|
||||||
|
* 使用SimpleHttpRequest替代RestTemplate,解决HTTPS连接兼容性问题
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class CtripDistTokenServiceImpl implements ICtripDistTokenService {
|
||||||
|
|
||||||
|
private static final long TOKEN_BUFFER_SECONDS = 60L;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CtripDistributorConfig config;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
private volatile String accessToken;
|
||||||
|
private volatile String refreshToken;
|
||||||
|
private volatile LocalDateTime tokenExpireTime;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public synchronized String getAccessToken() {
|
||||||
|
if (isTokenValid()) {
|
||||||
|
return accessToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (refreshToken != null && !refreshToken.isEmpty()) {
|
||||||
|
try {
|
||||||
|
refreshAccessToken();
|
||||||
|
if (isTokenValid()) {
|
||||||
|
return accessToken;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("刷新携程分销商Token失败,将重新获取新Token", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchNewToken();
|
||||||
|
if (!isTokenValid()) {
|
||||||
|
throw new RuntimeException("获取携程分销商AccessToken失败");
|
||||||
|
}
|
||||||
|
return accessToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isTokenValid() {
|
||||||
|
return accessToken != null
|
||||||
|
&& tokenExpireTime != null
|
||||||
|
&& LocalDateTime.now().plusSeconds(TOKEN_BUFFER_SECONDS).isBefore(tokenExpireTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fetchNewToken() {
|
||||||
|
String url = String.format("%s?aid=%s&sid=%s&key=%s",
|
||||||
|
config.getAuthUrl(), config.getAid(), config.getSid(), config.getKey());
|
||||||
|
log.info("获取新的携程分销商Token,请求URL: {}", url);
|
||||||
|
String responseBody = doGet(url);
|
||||||
|
log.info("携程分销商Token接口原始响应: {}", responseBody);
|
||||||
|
parseTokenResponse(responseBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void refreshAccessToken() {
|
||||||
|
String url = String.format("%s?aid=%s&sid=%s&refresh_token=%s",
|
||||||
|
config.getRefreshUrl(), config.getAid(), config.getSid(), refreshToken);
|
||||||
|
log.info("刷新携程分销商Token,请求URL: {}", url);
|
||||||
|
String responseBody = doGet(url);
|
||||||
|
log.info("携程分销商Token刷新响应: {}", responseBody);
|
||||||
|
parseTokenResponse(responseBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用SimpleHttpRequest发起GET请求
|
||||||
|
*/
|
||||||
|
private String doGet(String url) {
|
||||||
|
try {
|
||||||
|
SimpleHttpRequest request = new SimpleHttpRequest(url, SslUtil.createTrustAllHttpClient());
|
||||||
|
request.resultAsJsonString();
|
||||||
|
byte[] bytes = request.get().asBytes();
|
||||||
|
request.close();
|
||||||
|
return new String(bytes, "UTF-8");
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("携程分销商HTTP请求失败: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private void parseTokenResponse(String responseBody) {
|
||||||
|
if (responseBody == null || responseBody.isEmpty()) {
|
||||||
|
throw new RuntimeException("携程分销商Token接口返回为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> response;
|
||||||
|
try {
|
||||||
|
response = objectMapper.readValue(responseBody, Map.class);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("携程分销商Token响应解析失败: " + responseBody, e);
|
||||||
|
}
|
||||||
|
|
||||||
|
Object errCode = response.get("ErrCode");
|
||||||
|
int code = errCode == null ? 0 : Integer.parseInt(errCode.toString());
|
||||||
|
if (code != 0) {
|
||||||
|
throw new RuntimeException("携程分销商Token接口调用失败: " + response.get("ErrMsg"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Object expiresIn = response.get("Expires_In");
|
||||||
|
if (response.get("Access_Token") == null || response.get("Refresh_Token") == null || expiresIn == null) {
|
||||||
|
throw new RuntimeException("携程分销商Token响应缺少必要字段: " + responseBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.accessToken = response.get("Access_Token").toString();
|
||||||
|
this.refreshToken = response.get("Refresh_Token").toString();
|
||||||
|
this.tokenExpireTime = LocalDateTime.now().plusSeconds(Long.parseLong(expiresIn.toString()));
|
||||||
|
log.info("携程分销商Token更新成功,过期时间: {}", tokenExpireTime);
|
||||||
|
}
|
||||||
|
}
|
||||||
+90
@@ -0,0 +1,90 @@
|
|||||||
|
package com.central.coupon.task;
|
||||||
|
|
||||||
|
import com.central.coupon.entity.CtripDistOrder;
|
||||||
|
import com.central.coupon.mapper.CtripDistOrderMapper;
|
||||||
|
import com.central.coupon.model.CtripDistBookingDetailResponse;
|
||||||
|
import com.central.coupon.service.ICtripDistApiService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class CtripDistConsumeTask {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CtripDistOrderMapper ctripDistOrderMapper;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ICtripDistApiService ctripDistApiService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每天凌晨3点执行:核销2天前创建且未核销的携程分销订单
|
||||||
|
*/
|
||||||
|
@Scheduled(cron = "0 0 3 * * ?")
|
||||||
|
public void autoConsumeCtripDistOrders() {
|
||||||
|
log.info("开始自动核销携程分销订单");
|
||||||
|
try {
|
||||||
|
List<CtripDistOrder> pendingOrders = ctripDistOrderMapper.selectPendingConsumeOrders(2);
|
||||||
|
log.info("待核销的携程分销订单数量: {}", pendingOrders.size());
|
||||||
|
|
||||||
|
for (CtripDistOrder order : pendingOrders) {
|
||||||
|
try {
|
||||||
|
consumeOrder(order);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("核销携程分销订单失败,orderNo: {}", order.getOrderNo(), e);
|
||||||
|
order.setConsumeStatus(2);
|
||||||
|
order.setErrorMsg("核销失败: " + e.getMessage());
|
||||||
|
ctripDistOrderMapper.updateById(order);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
log.info("携程分销订单自动核销完成");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("自动核销携程分销订单任务异常", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 核销单个订单
|
||||||
|
* 先查询携程订单状态确认为CONFIRMED,然后标记为已核销
|
||||||
|
*/
|
||||||
|
private void consumeOrder(CtripDistOrder order) {
|
||||||
|
log.info("开始核销携程分销订单,orderNo: {}, ctripOrderId: {}",
|
||||||
|
order.getOrderNo(), order.getCtripOrderId());
|
||||||
|
|
||||||
|
// 查询携程订单当前状态
|
||||||
|
CtripDistBookingDetailResponse detail = ctripDistApiService.getOrderDetail(order.getCtripOrderId());
|
||||||
|
if (detail != null && detail.isSuccess() && detail.getData() != null
|
||||||
|
&& detail.getData().getOrder() != null) {
|
||||||
|
String ctripStatus = detail.getData().getOrder().getOrderStatus();
|
||||||
|
log.info("携程订单当前状态: {}, orderNo: {}", ctripStatus, order.getOrderNo());
|
||||||
|
|
||||||
|
if ("CONFIRMED".equals(ctripStatus)) {
|
||||||
|
// 订单状态正常,执行核销
|
||||||
|
order.setConsumeStatus(1);
|
||||||
|
order.setConsumeTime(LocalDateTime.now());
|
||||||
|
order.setCtripOrderStatus("CONSUMED");
|
||||||
|
ctripDistOrderMapper.updateById(order);
|
||||||
|
log.info("携程分销订单核销成功,orderNo: {}", order.getOrderNo());
|
||||||
|
} else if ("CANCELLED".equals(ctripStatus) || "CANCELLED_RESERVATION".equals(ctripStatus)) {
|
||||||
|
// 订单已被取消,更新状态
|
||||||
|
order.setCtripOrderStatus(ctripStatus);
|
||||||
|
order.setConsumeStatus(2);
|
||||||
|
order.setErrorMsg("携程订单已被取消,无法核销");
|
||||||
|
ctripDistOrderMapper.updateById(order);
|
||||||
|
log.warn("携程订单已取消,跳过核销,orderNo: {}", order.getOrderNo());
|
||||||
|
} else {
|
||||||
|
log.warn("携程订单状态不适合核销: {},orderNo: {}", ctripStatus, order.getOrderNo());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.error("查询携程订单详情失败,orderNo: {}", order.getOrderNo());
|
||||||
|
order.setConsumeStatus(2);
|
||||||
|
order.setErrorMsg("查询携程订单详情失败");
|
||||||
|
ctripDistOrderMapper.updateById(order);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package com.central.coupon.util;
|
||||||
|
|
||||||
|
import org.apache.http.client.HttpClient;
|
||||||
|
import org.apache.http.client.config.RequestConfig;
|
||||||
|
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
||||||
|
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||||
|
import org.apache.http.impl.client.HttpClients;
|
||||||
|
|
||||||
|
import javax.net.ssl.SSLContext;
|
||||||
|
import javax.net.ssl.TrustManager;
|
||||||
|
import javax.net.ssl.X509TrustManager;
|
||||||
|
import java.security.cert.X509Certificate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SSL工具类
|
||||||
|
* 提供信任所有证书的HttpClient,解决携程HTTPS证书信任链问题
|
||||||
|
*/
|
||||||
|
public class SslUtil {
|
||||||
|
|
||||||
|
private SslUtil() {}
|
||||||
|
|
||||||
|
/** 默认超时时间:15秒(携程可订/下单接口要求15s超时) */
|
||||||
|
private static final int DEFAULT_TIMEOUT_MS = 15000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建信任所有证书的HttpClient(使用默认15秒超��)
|
||||||
|
*/
|
||||||
|
public static HttpClient createTrustAllHttpClient() {
|
||||||
|
return createTrustAllHttpClient(DEFAULT_TIMEOUT_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建信任所有证书的HttpClient(自定义超时)
|
||||||
|
*
|
||||||
|
* @param timeoutMs 超时时间(毫秒),同时设置连接超时和读取超时
|
||||||
|
*/
|
||||||
|
public static HttpClient createTrustAllHttpClient(int timeoutMs) {
|
||||||
|
try {
|
||||||
|
SSLContext sslContext = SSLContext.getInstance("TLS");
|
||||||
|
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
|
||||||
|
@Override
|
||||||
|
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public X509Certificate[] getAcceptedIssuers() {
|
||||||
|
return new X509Certificate[0];
|
||||||
|
}
|
||||||
|
}}, new java.security.SecureRandom());
|
||||||
|
|
||||||
|
SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(
|
||||||
|
sslContext, NoopHostnameVerifier.INSTANCE);
|
||||||
|
|
||||||
|
RequestConfig requestConfig = RequestConfig.custom()
|
||||||
|
.setConnectTimeout(timeoutMs)
|
||||||
|
.setSocketTimeout(timeoutMs)
|
||||||
|
.setConnectionRequestTimeout(timeoutMs)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
return HttpClients.custom()
|
||||||
|
.setSSLSocketFactory(sslFactory)
|
||||||
|
.setDefaultRequestConfig(requestConfig)
|
||||||
|
.build();
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("创建信任所有证书的HttpClient失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<?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.coupon.mapper.CtripDistOrderMapper">
|
||||||
|
|
||||||
|
<select id="selectByOrderNo" resultType="com.central.coupon.entity.CtripDistOrder">
|
||||||
|
SELECT *
|
||||||
|
FROM t_ctrip_dist_order
|
||||||
|
WHERE order_no = #{orderNo}
|
||||||
|
AND deleted = 0
|
||||||
|
LIMIT 1
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select id="selectPendingConsumeOrders" resultType="com.central.coupon.entity.CtripDistOrder">
|
||||||
|
SELECT *
|
||||||
|
FROM t_ctrip_dist_order
|
||||||
|
WHERE ctrip_order_status = 'CONFIRMED'
|
||||||
|
AND consume_status = 0
|
||||||
|
AND deleted = 0
|
||||||
|
AND create_time <= DATE_SUB(NOW(), INTERVAL #{daysAgo} DAY)
|
||||||
|
ORDER BY create_time ASC
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select id="selectByDistributorOrderId" resultType="com.central.coupon.entity.CtripDistOrder">
|
||||||
|
SELECT *
|
||||||
|
FROM t_ctrip_dist_order
|
||||||
|
WHERE distributor_order_id = #{distributorOrderId}
|
||||||
|
AND deleted = 0
|
||||||
|
LIMIT 1
|
||||||
|
</select>
|
||||||
|
</mapper>
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
-- 携程分销订单关联表(我方订单 ↔ 携程订单)
|
||||||
|
-- 用途:记录本地订单与携程分销订单的对应关系,跟踪核销和退款状态
|
||||||
|
CREATE TABLE IF NOT EXISTS `t_ctrip_dist_order` (
|
||||||
|
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||||
|
`tenant_id` varchar(12) DEFAULT '000000' COMMENT '租户ID',
|
||||||
|
`order_no` varchar(100) NOT NULL COMMENT '本地订单号(order-center的订单号)',
|
||||||
|
`ctrip_order_id` bigint(20) DEFAULT NULL COMMENT '携程订单ID(/book返回的orderId)',
|
||||||
|
`ctrip_product_id` bigint(20) NOT NULL COMMENT '携程产品ID',
|
||||||
|
`ctrip_package_id` bigint(20) DEFAULT NULL COMMENT '携程套餐ID',
|
||||||
|
`ctrip_resource_id` bigint(20) DEFAULT NULL COMMENT '携程资源ID',
|
||||||
|
`distributor_order_id` varchar(100) NOT NULL COMMENT '分销商订单ID(传给携程的唯一标识)',
|
||||||
|
`order_amount` decimal(10,2) DEFAULT NULL COMMENT '订单金额',
|
||||||
|
`currency` varchar(10) DEFAULT 'CNY' COMMENT '货币类型',
|
||||||
|
`ctrip_order_status` varchar(50) DEFAULT 'PENDING' COMMENT '携程订单状态',
|
||||||
|
`consume_status` tinyint(1) DEFAULT 0 COMMENT '核销状态(0:未核销,1:已核销,2:核销失败)',
|
||||||
|
`consume_time` datetime DEFAULT NULL COMMENT '核销时间',
|
||||||
|
`refund_status` tinyint(1) DEFAULT 0 COMMENT '退款状态(0:未退款,1:已退款,2:退款失败)',
|
||||||
|
`refund_time` datetime DEFAULT NULL COMMENT '退款时间',
|
||||||
|
`refund_amount` decimal(10,2) DEFAULT NULL COMMENT '退款金额',
|
||||||
|
`error_msg` varchar(500) DEFAULT NULL COMMENT '错误信息(创建失败/核销失败/退款失败时记录)',
|
||||||
|
`retry_count` int(11) DEFAULT 0 COMMENT '重试次数',
|
||||||
|
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
|
||||||
|
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||||
|
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
`deleted` tinyint(1) DEFAULT 0 COMMENT '是否删除',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_order_no` (`order_no`),
|
||||||
|
UNIQUE KEY `uk_distributor_order_id` (`distributor_order_id`),
|
||||||
|
KEY `idx_ctrip_order_id` (`ctrip_order_id`),
|
||||||
|
KEY `idx_consume_status` (`consume_status`),
|
||||||
|
KEY `idx_create_time` (`create_time`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='携程分销订单关联表';
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package com.central.device.entity;
|
package com.central.device.boat.entity;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.annotation.*;
|
import com.baomidou.mybatisplus.annotation.*;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package com.central.device.entity;
|
package com.central.device.boat.entity;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.annotation.*;
|
import com.baomidou.mybatisplus.annotation.*;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package com.central.device.entity;
|
package com.central.device.boat.entity;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.annotation.*;
|
import com.baomidou.mybatisplus.annotation.*;
|
||||||
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
|
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package com.central.device.entity;
|
package com.central.device.boat.entity;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.annotation.*;
|
import com.baomidou.mybatisplus.annotation.*;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package com.central.device.entity;
|
package com.central.device.boat.entity;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.annotation.*;
|
import com.baomidou.mybatisplus.annotation.*;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package com.central.device.entity;
|
package com.central.device.boat.entity;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.annotation.*;
|
import com.baomidou.mybatisplus.annotation.*;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package com.central.device.entity;
|
package com.central.device.boat.entity;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.annotation.*;
|
import com.baomidou.mybatisplus.annotation.*;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package com.central.device.entity;
|
package com.central.device.boat.entity;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.annotation.*;
|
import com.baomidou.mybatisplus.annotation.*;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
+369
@@ -0,0 +1,369 @@
|
|||||||
|
package com.central.device.boat.manager;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSONObject;
|
||||||
|
import com.central.device.websocket.client.JetLinksWebSocketClient;
|
||||||
|
import com.central.device.websocket.config.WebSocketProperties;
|
||||||
|
import com.central.device.websocket.model.CommandStatus;
|
||||||
|
import com.central.device.websocket.model.DeviceCommand;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 无人船命令管理器
|
||||||
|
* 负责无人船命令队列管理、发送、重试、超时处理
|
||||||
|
* 复用全局JetLinksWebSocketClient发送命令,使用 ship 产品标识
|
||||||
|
*
|
||||||
|
* @author dzc
|
||||||
|
* @date 2026-04-07
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class BoatCommandManager {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private WebSocketProperties properties;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private JetLinksWebSocketClient jetLinksWebSocketClient;
|
||||||
|
|
||||||
|
/** 无人船产品标识 */
|
||||||
|
public static final String PRODUCT_BOAT = "ship";
|
||||||
|
|
||||||
|
/** 待发送命令队列: deviceSn -> Queue<DeviceCommand> */
|
||||||
|
private final ConcurrentHashMap<String, ConcurrentLinkedQueue<DeviceCommand>> commandQueues = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
/** 已发送等待响应的命令: commandId -> DeviceCommand */
|
||||||
|
private final ConcurrentHashMap<String, DeviceCommand> pendingCommands = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
/** 延迟执行器(用于重试) */
|
||||||
|
private final ScheduledExecutorService retryExecutor = Executors.newScheduledThreadPool(2);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送命令
|
||||||
|
*
|
||||||
|
* @param deviceSn 设备SN
|
||||||
|
* @param commandType 命令类型(flighttask_prepare/flighttask_pause/flighttask_recovery/flighttask_undo)
|
||||||
|
* @param params 命令参数
|
||||||
|
* @return 命令ID
|
||||||
|
*/
|
||||||
|
public String sendCommand(String deviceSn, String commandType, JSONObject params) {
|
||||||
|
DeviceCommand command = DeviceCommand.builder()
|
||||||
|
.commandId(UUID.randomUUID().toString())
|
||||||
|
.deviceSn(deviceSn)
|
||||||
|
.commandType(commandType)
|
||||||
|
.params(params != null ? params : new JSONObject())
|
||||||
|
.status(CommandStatus.PENDING)
|
||||||
|
.createTime(System.currentTimeMillis())
|
||||||
|
.sendTime(0)
|
||||||
|
.expireTime(System.currentTimeMillis() + properties.getCommand().getDefaultTimeout())
|
||||||
|
.retryCount(0)
|
||||||
|
.maxRetry(properties.getCommand().getMaxRetry())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
log.info("[无人船] 创建命令: commandId={}, device={}, type={}",
|
||||||
|
command.getCommandId(), deviceSn, commandType);
|
||||||
|
|
||||||
|
// 检查全局WebSocket连接状态,未连接则自动连接
|
||||||
|
if (!jetLinksWebSocketClient.isConnected()) {
|
||||||
|
log.info("[无人船] WebSocket未连接,自动建立连接: commandId={}", command.getCommandId());
|
||||||
|
jetLinksWebSocketClient.connect();
|
||||||
|
|
||||||
|
int waitCount = 0;
|
||||||
|
while (!jetLinksWebSocketClient.isConnected() && waitCount < 50) {
|
||||||
|
try {
|
||||||
|
Thread.sleep(100);
|
||||||
|
waitCount++;
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
log.error("[无人船] 等待连接被中断");
|
||||||
|
addToQueue(command);
|
||||||
|
return command.getCommandId();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (jetLinksWebSocketClient.isConnected()) {
|
||||||
|
sendCommandImmediately(command);
|
||||||
|
} else {
|
||||||
|
log.warn("[无人船] WebSocket连接失败,命令加入队列: commandId={}, device={}",
|
||||||
|
command.getCommandId(), deviceSn);
|
||||||
|
addToQueue(command);
|
||||||
|
}
|
||||||
|
|
||||||
|
return command.getCommandId();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 立即发送命令(通过全局WebSocket客户端)
|
||||||
|
* topic 使用 /device-message-sender/ship/{deviceSn}
|
||||||
|
*/
|
||||||
|
private void sendCommandImmediately(DeviceCommand command) {
|
||||||
|
try {
|
||||||
|
command.setStatus(CommandStatus.SENDING);
|
||||||
|
command.setSendTime(System.currentTimeMillis());
|
||||||
|
|
||||||
|
// 构造指令内容 (properties)
|
||||||
|
JSONObject cmdProperties = buildCommandProperties(command);
|
||||||
|
|
||||||
|
// 构造 parameter
|
||||||
|
JSONObject parameter = new JSONObject();
|
||||||
|
parameter.put("messageType", "WRITE_PROPERTY");
|
||||||
|
parameter.put("properties", cmdProperties);
|
||||||
|
|
||||||
|
JSONObject headers = new JSONObject();
|
||||||
|
headers.put("async", false);
|
||||||
|
parameter.put("headers", headers);
|
||||||
|
|
||||||
|
// 构造完整消息(使用 ship 产品标识)
|
||||||
|
JSONObject message = new JSONObject();
|
||||||
|
message.put("type", "sub");
|
||||||
|
message.put("topic", "/device-message-sender/" + PRODUCT_BOAT + "/" + command.getDeviceSn());
|
||||||
|
message.put("parameter", parameter);
|
||||||
|
message.put("id", command.getCommandId());
|
||||||
|
|
||||||
|
String messageJson = message.toJSONString();
|
||||||
|
log.info("[无人船] 发送命令消息: {}", messageJson);
|
||||||
|
jetLinksWebSocketClient.send(messageJson);
|
||||||
|
|
||||||
|
command.setStatus(CommandStatus.SENT);
|
||||||
|
pendingCommands.put(command.getCommandId(), command);
|
||||||
|
|
||||||
|
log.info("[无人船] 命令发送成功: commandId={}, device={}, type={}",
|
||||||
|
command.getCommandId(), command.getDeviceSn(), command.getCommandType());
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[无人船] 命令发送失败: commandId={}, error={}", command.getCommandId(), e.getMessage());
|
||||||
|
command.setStatus(CommandStatus.FAILED);
|
||||||
|
command.setErrorMsg(e.getMessage());
|
||||||
|
retryCommand(command);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据命令类型构造 properties 内容(无人船专用)
|
||||||
|
*
|
||||||
|
* 与无人机的关键区别:
|
||||||
|
* 1. 无人船的暂停/恢复/终止都需要 order_no 参数
|
||||||
|
* 2. 无人船的开始任务需要 order_no、wayline_link_url、file_md5、stream_urls
|
||||||
|
*/
|
||||||
|
private JSONObject buildCommandProperties(DeviceCommand command) {
|
||||||
|
JSONObject cmdProperties = new JSONObject();
|
||||||
|
JSONObject data = new JSONObject();
|
||||||
|
String method = command.getCommandType();
|
||||||
|
JSONObject params = command.getParams();
|
||||||
|
|
||||||
|
switch (method) {
|
||||||
|
case "flighttask_prepare":
|
||||||
|
// 开始任务
|
||||||
|
data.put("order_no", params.getString("order_no"));
|
||||||
|
data.put("wayline_link_url", params.getString("wayline_link_url"));
|
||||||
|
data.put("file_md5", params.getString("file_md5"));
|
||||||
|
if (params.containsKey("stream_urls")) {
|
||||||
|
data.put("stream_urls", params.get("stream_urls"));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "flighttask_pause":
|
||||||
|
// 暂停任务
|
||||||
|
data.put("order_no", params.getString("order_no"));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "flighttask_recovery":
|
||||||
|
// 恢复任务
|
||||||
|
data.put("order_no", params.getString("order_no"));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "flighttask_undo":
|
||||||
|
// 终止任务
|
||||||
|
if (params.containsKey("order_no")) {
|
||||||
|
data.put("order_no", params.getString("order_no"));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
data = params;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
cmdProperties.put("method", method);
|
||||||
|
cmdProperties.put("data", data);
|
||||||
|
return cmdProperties;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加入队列
|
||||||
|
*/
|
||||||
|
private void addToQueue(DeviceCommand command) {
|
||||||
|
ConcurrentLinkedQueue<DeviceCommand> queue = commandQueues
|
||||||
|
.computeIfAbsent(command.getDeviceSn(), k -> new ConcurrentLinkedQueue<>());
|
||||||
|
|
||||||
|
if (queue.size() >= properties.getCommand().getQueueMaxSize()) {
|
||||||
|
log.error("[无人船] 设备 {} 命令队列已满({}), 拒绝新命令: {}",
|
||||||
|
command.getDeviceSn(), properties.getCommand().getQueueMaxSize(), command.getCommandId());
|
||||||
|
command.setStatus(CommandStatus.FAILED);
|
||||||
|
command.setErrorMsg("命令队列已满");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
queue.offer(command);
|
||||||
|
log.info("[无人船] 命令已加入队列: commandId={}, device={}, 队列长度={}",
|
||||||
|
command.getCommandId(), command.getDeviceSn(), queue.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WebSocket重连后处理所有队列
|
||||||
|
* 由外部在 WebSocket 重连成功后调用
|
||||||
|
*/
|
||||||
|
public void onWebSocketReconnected() {
|
||||||
|
log.info("[无人船] WebSocket重连成功,开始处理命令队列");
|
||||||
|
|
||||||
|
if (commandQueues.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
int totalProcessed = 0;
|
||||||
|
int totalExpired = 0;
|
||||||
|
|
||||||
|
for (String deviceSn : commandQueues.keySet()) {
|
||||||
|
ConcurrentLinkedQueue<DeviceCommand> queue = commandQueues.get(deviceSn);
|
||||||
|
if (queue == null || queue.isEmpty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (!queue.isEmpty()) {
|
||||||
|
DeviceCommand command = queue.poll();
|
||||||
|
|
||||||
|
if (System.currentTimeMillis() > command.getExpireTime()) {
|
||||||
|
command.setStatus(CommandStatus.EXPIRED);
|
||||||
|
totalExpired++;
|
||||||
|
log.warn("[无人船] 命令已过期: commandId={}, device={}", command.getCommandId(), deviceSn);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
sendCommandImmediately(command);
|
||||||
|
totalProcessed++;
|
||||||
|
|
||||||
|
try {
|
||||||
|
Thread.sleep(100);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (totalProcessed > 0 || totalExpired > 0) {
|
||||||
|
log.info("[无人船] 命令队列处理完成: 重发={}, 过期={}", totalProcessed, totalExpired);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 命令重试
|
||||||
|
*/
|
||||||
|
private void retryCommand(DeviceCommand command) {
|
||||||
|
if (command.getRetryCount() >= command.getMaxRetry()) {
|
||||||
|
log.error("[无人船] 命令重试次数超限: commandId={}, device={}",
|
||||||
|
command.getCommandId(), command.getDeviceSn());
|
||||||
|
command.setStatus(CommandStatus.FAILED);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
command.setRetryCount(command.getRetryCount() + 1);
|
||||||
|
log.info("[无人船] 命令准备重试 ({}/{}): commandId={}",
|
||||||
|
command.getRetryCount(), command.getMaxRetry(), command.getCommandId());
|
||||||
|
|
||||||
|
long delay = (long) Math.pow(2, command.getRetryCount()) * properties.getCommand().getRetryDelayBase();
|
||||||
|
|
||||||
|
retryExecutor.schedule(() -> {
|
||||||
|
if (jetLinksWebSocketClient.isConnected()) {
|
||||||
|
sendCommandImmediately(command);
|
||||||
|
} else {
|
||||||
|
addToQueue(command);
|
||||||
|
}
|
||||||
|
}, delay, TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接收设备命令响应
|
||||||
|
*/
|
||||||
|
public void handleCommandResponse(String commandId, boolean success, String message) {
|
||||||
|
DeviceCommand command = pendingCommands.remove(commandId);
|
||||||
|
if (command == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (success) {
|
||||||
|
command.setStatus(CommandStatus.SUCCESS);
|
||||||
|
log.info("[无人船] 命令执行成功: commandId={}, device={}, type={}",
|
||||||
|
commandId, command.getDeviceSn(), command.getCommandType());
|
||||||
|
} else {
|
||||||
|
command.setStatus(CommandStatus.FAILED);
|
||||||
|
command.setErrorMsg(message);
|
||||||
|
log.error("[无人船] 命令执行失败: commandId={}, device={}, type={}, error={}",
|
||||||
|
commandId, command.getDeviceSn(), command.getCommandType(), message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 定时清理过期命令
|
||||||
|
*/
|
||||||
|
@Scheduled(fixedRateString = "${device.websocket.command.cleanup-interval:10000}")
|
||||||
|
public void cleanupExpiredCommands() {
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
int queueExpiredCount = 0;
|
||||||
|
AtomicInteger pendingTimeoutCount = new AtomicInteger(0);
|
||||||
|
|
||||||
|
for (ConcurrentLinkedQueue<DeviceCommand> queue : commandQueues.values()) {
|
||||||
|
for (DeviceCommand command : queue) {
|
||||||
|
if (now > command.getExpireTime()) {
|
||||||
|
if (queue.remove(command)) {
|
||||||
|
command.setStatus(CommandStatus.EXPIRED);
|
||||||
|
queueExpiredCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pendingCommands.entrySet().removeIf(entry -> {
|
||||||
|
DeviceCommand command = entry.getValue();
|
||||||
|
if (now > command.getExpireTime()) {
|
||||||
|
command.setStatus(CommandStatus.TIMEOUT);
|
||||||
|
pendingTimeoutCount.incrementAndGet();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (queueExpiredCount > 0 || pendingTimeoutCount.get() > 0) {
|
||||||
|
log.info("[无人船] 清理过期命令: 队列过期={}, 响应超时={}", queueExpiredCount, pendingTimeoutCount.get());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询命令状态
|
||||||
|
*/
|
||||||
|
public CommandStatus getCommandStatus(String commandId) {
|
||||||
|
DeviceCommand command = pendingCommands.get(commandId);
|
||||||
|
if (command != null) {
|
||||||
|
return command.getStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
for (ConcurrentLinkedQueue<DeviceCommand> queue : commandQueues.values()) {
|
||||||
|
Optional<DeviceCommand> found = queue.stream()
|
||||||
|
.filter(cmd -> cmd.getCommandId().equals(commandId))
|
||||||
|
.findFirst();
|
||||||
|
if (found.isPresent()) {
|
||||||
|
return found.get().getStatus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
+158
@@ -0,0 +1,158 @@
|
|||||||
|
package com.central.device.boat.manager;
|
||||||
|
|
||||||
|
import com.central.device.boat.model.BoatSubscriptionTopic;
|
||||||
|
import com.central.device.websocket.client.JetLinksWebSocketClient;
|
||||||
|
import com.central.device.websocket.handler.DeviceMessageHandler;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 无人船设备订阅管理器
|
||||||
|
* 管理无人船设备的 WebSocket 主题订阅/取消订阅
|
||||||
|
* 使用 BoatSubscriptionTopic(ship 产品),通过 JetLinksWebSocketClient 的 subscribeRawTopic/unsubscribeRawTopic 方法
|
||||||
|
* 确保 topic 被纳入 subscribedTopics 跟踪,消息路由不被过滤
|
||||||
|
*
|
||||||
|
* @author dzc
|
||||||
|
* @date 2026-04-07
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class BoatSubscriptionManager {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private JetLinksWebSocketClient jetLinksWebSocketClient;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private DeviceMessageHandler messageHandler;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订阅无人船设备(上线、离线、状态事件)
|
||||||
|
*
|
||||||
|
* @param deviceSn 设备SN
|
||||||
|
* @param tenantId 租户ID
|
||||||
|
*/
|
||||||
|
public void subscribeBoatDevice(String deviceSn, String tenantId) {
|
||||||
|
if (deviceSn == null || deviceSn.trim().isEmpty()) {
|
||||||
|
log.warn("[无人船] 设备SN为空,无法订阅");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("[无人船] 订阅设备: deviceSn={}, tenantId={}", deviceSn, tenantId);
|
||||||
|
|
||||||
|
try {
|
||||||
|
ensureConnected();
|
||||||
|
|
||||||
|
messageHandler.addDevice(deviceSn, 0L, tenantId);
|
||||||
|
|
||||||
|
jetLinksWebSocketClient.subscribeRawTopic(
|
||||||
|
BoatSubscriptionTopic.BOAT_ONLINE.getTopic(deviceSn), deviceSn);
|
||||||
|
jetLinksWebSocketClient.subscribeRawTopic(
|
||||||
|
BoatSubscriptionTopic.BOAT_OFFLINE.getTopic(deviceSn), deviceSn);
|
||||||
|
jetLinksWebSocketClient.subscribeRawTopic(
|
||||||
|
BoatSubscriptionTopic.BOAT_EVENT_FIRE_ALARM.getTopic(deviceSn), deviceSn);
|
||||||
|
|
||||||
|
log.info("[无人船] 设备 {} 订阅成功", deviceSn);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[无人船] 设备 {} 订阅失败: {}", deviceSn, e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订阅无人船遥测数据(进入操控台时调用)
|
||||||
|
*
|
||||||
|
* @param deviceSn 设备SN
|
||||||
|
*/
|
||||||
|
public void subscribeBoatTelemetry(String deviceSn) {
|
||||||
|
if (deviceSn == null || deviceSn.trim().isEmpty()) {
|
||||||
|
log.warn("[无人船] 设备SN为空,无法订阅遥测");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("[无人船] 订阅遥测数据: deviceSn={}", deviceSn);
|
||||||
|
|
||||||
|
try {
|
||||||
|
ensureConnected();
|
||||||
|
jetLinksWebSocketClient.subscribeRawTopic(
|
||||||
|
BoatSubscriptionTopic.BOAT_EVENT_MSG_ALARM.getTopic(deviceSn), deviceSn);
|
||||||
|
log.info("[无人船] 遥测数据 {} 订阅成功", deviceSn);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[无人船] 订阅遥测数据 {} 失败: {}", deviceSn, e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消订阅无人船设备
|
||||||
|
*
|
||||||
|
* @param deviceSn 设备SN
|
||||||
|
*/
|
||||||
|
public void unsubscribeBoatDevice(String deviceSn) {
|
||||||
|
if (deviceSn == null || deviceSn.trim().isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("[无人船] 取消订阅设备: deviceSn={}", deviceSn);
|
||||||
|
|
||||||
|
try {
|
||||||
|
jetLinksWebSocketClient.unsubscribeRawTopic(
|
||||||
|
BoatSubscriptionTopic.BOAT_ONLINE.getTopic(deviceSn), deviceSn);
|
||||||
|
jetLinksWebSocketClient.unsubscribeRawTopic(
|
||||||
|
BoatSubscriptionTopic.BOAT_OFFLINE.getTopic(deviceSn), deviceSn);
|
||||||
|
jetLinksWebSocketClient.unsubscribeRawTopic(
|
||||||
|
BoatSubscriptionTopic.BOAT_EVENT_FIRE_ALARM.getTopic(deviceSn), deviceSn);
|
||||||
|
jetLinksWebSocketClient.unsubscribeRawTopic(
|
||||||
|
BoatSubscriptionTopic.BOAT_EVENT_MSG_ALARM.getTopic(deviceSn), deviceSn);
|
||||||
|
|
||||||
|
messageHandler.removeDevice(deviceSn);
|
||||||
|
log.info("[无人船] 设备 {} 订阅已取消", deviceSn);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[无人船] 取消订阅设备 {} 失败: {}", deviceSn, e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消订阅无人船遥测数据(退出操控台时调用)
|
||||||
|
*
|
||||||
|
* @param deviceSn 设备SN
|
||||||
|
*/
|
||||||
|
public void unsubscribeBoatTelemetry(String deviceSn) {
|
||||||
|
if (deviceSn == null || deviceSn.trim().isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("[无人船] 取消订阅遥测数据: deviceSn={}", deviceSn);
|
||||||
|
|
||||||
|
try {
|
||||||
|
jetLinksWebSocketClient.unsubscribeRawTopic(
|
||||||
|
BoatSubscriptionTopic.BOAT_EVENT_MSG_ALARM.getTopic(deviceSn), deviceSn);
|
||||||
|
log.info("[无人船] 遥测数据 {} 订阅已取消", deviceSn);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[无人船] 取消订阅遥测数据 {} 失败: {}", deviceSn, e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 确保 WebSocket 已连接
|
||||||
|
*/
|
||||||
|
private void ensureConnected() {
|
||||||
|
if (!jetLinksWebSocketClient.isConnected()) {
|
||||||
|
log.info("[无人船] WebSocket未连接,自动建立连接");
|
||||||
|
jetLinksWebSocketClient.connect();
|
||||||
|
|
||||||
|
int waitCount = 0;
|
||||||
|
while (!jetLinksWebSocketClient.isConnected() && waitCount < 50) {
|
||||||
|
try {
|
||||||
|
Thread.sleep(100);
|
||||||
|
waitCount++;
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new RuntimeException("等待WebSocket连接被中断");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!jetLinksWebSocketClient.isConnected()) {
|
||||||
|
throw new RuntimeException("WebSocket连接超时");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
package com.central.device.boat.model;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 无人船WebSocket订阅主题
|
||||||
|
* 基于JetLinks平台的主题订阅模式,使用 ship 产品标识
|
||||||
|
*
|
||||||
|
* @author dzc
|
||||||
|
* @date 2026-04-07
|
||||||
|
*/
|
||||||
|
public enum BoatSubscriptionTopic {
|
||||||
|
|
||||||
|
/** 无人船设备上线 */
|
||||||
|
BOAT_ONLINE("/device/ship/{deviceSn}/online"),
|
||||||
|
|
||||||
|
/** 无人船设备离线 */
|
||||||
|
BOAT_OFFLINE("/device/ship/{deviceSn}/offline"),
|
||||||
|
|
||||||
|
/** 无人船设备状态事件 */
|
||||||
|
BOAT_EVENT_FIRE_ALARM("/device/ship/{deviceSn}/message/event/fire_alarm"),
|
||||||
|
|
||||||
|
/** 无人船遥测数据事件 */
|
||||||
|
BOAT_EVENT_MSG_ALARM("/device/ship/{deviceSn}/message/event/msg_alarm"),
|
||||||
|
|
||||||
|
/** 无人船属性上报 */
|
||||||
|
BOAT_PROPERTY_REPORT("/device/ship/{deviceSn}/message/property/report");
|
||||||
|
|
||||||
|
private final String topicPattern;
|
||||||
|
|
||||||
|
BoatSubscriptionTopic(String topicPattern) {
|
||||||
|
this.topicPattern = topicPattern;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取主题(替换deviceSn占位符)
|
||||||
|
*/
|
||||||
|
public String getTopic(String deviceSn) {
|
||||||
|
return topicPattern.replace("{deviceSn}", deviceSn);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取主题模式
|
||||||
|
*/
|
||||||
|
public String getTopicPattern() {
|
||||||
|
return topicPattern;
|
||||||
|
}
|
||||||
|
}
|
||||||
+325
@@ -0,0 +1,325 @@
|
|||||||
|
package com.central.device.boat.sse;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSON;
|
||||||
|
import com.alibaba.fastjson.JSONObject;
|
||||||
|
import com.central.device.boat.manager.BoatSubscriptionManager;
|
||||||
|
import com.central.device.sse.model.EmitterWrapper;
|
||||||
|
import com.central.device.websocket.handler.DeviceMessageHandler;
|
||||||
|
import com.central.device.websocket.manager.SubscriptionPoolService;
|
||||||
|
import com.central.device.websocket.manager.SubscriptionPoolService.TopicType;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||||
|
|
||||||
|
import jakarta.annotation.PostConstruct;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 无人船SSE发射器管理器
|
||||||
|
* 管理无人船前端SSE连接、触发WebSocket订阅、推送设备实时数据
|
||||||
|
*
|
||||||
|
* 数据流:
|
||||||
|
* JetLinks IoT → JetLinksWebSocketClient → DeviceMessageHandler
|
||||||
|
* → msgAlarmCallback → BoatSseEmitterManager.sendBoatDataUpdate() → SSE客户端
|
||||||
|
*
|
||||||
|
* 复用组件:
|
||||||
|
* - BoatSubscriptionManager: WebSocket主题订阅/取消
|
||||||
|
* - SubscriptionPoolService: Redis订阅池(多客户端隔离)
|
||||||
|
* - DeviceMessageHandler: 注册回调接收IoT消息
|
||||||
|
* - EmitterWrapper: SSE连接包装器
|
||||||
|
*
|
||||||
|
* @author dzc
|
||||||
|
* @date 2026-04-07
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class BoatSseEmitterManager {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private BoatSubscriptionManager boatSubscriptionManager;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private DeviceMessageHandler messageHandler;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private SubscriptionPoolService subscriptionPoolService;
|
||||||
|
|
||||||
|
/** SSE连接池: sessionId -> EmitterWrapper */
|
||||||
|
private final ConcurrentHashMap<String, EmitterWrapper> emitters = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
/** 设备订阅本地引用计数: deviceSn -> count */
|
||||||
|
private final ConcurrentHashMap<String, Integer> deviceRefCount = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
private ScheduledExecutorService heartbeatExecutor;
|
||||||
|
private ScheduledExecutorService cleanupExecutor;
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
public void init() {
|
||||||
|
startHeartbeat();
|
||||||
|
startOrphanCleanup();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 添加无人船SSE连接
|
||||||
|
* 创建SSE连接 + 触发WebSocket订阅 + Redis订阅池 + 注册消息回调
|
||||||
|
*/
|
||||||
|
public SseEmitter addEmitter(String sessionId, String deviceSn, String tenantId) {
|
||||||
|
// 移除重复连接
|
||||||
|
if (emitters.containsKey(sessionId)) {
|
||||||
|
log.warn("[无人船SSE] 检测到重复连接,先移除: sessionId={}", sessionId);
|
||||||
|
removeEmitter(sessionId, deviceSn);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建SseEmitter(5分钟超时,配合心跳续期)
|
||||||
|
SseEmitter emitter = new SseEmitter(5 * 60 * 1000L);
|
||||||
|
|
||||||
|
emitter.onCompletion(() -> {
|
||||||
|
log.info("[无人船SSE] 连接完成: session={}, deviceSn={}", sessionId, deviceSn);
|
||||||
|
removeEmitter(sessionId, deviceSn);
|
||||||
|
});
|
||||||
|
emitter.onTimeout(() -> {
|
||||||
|
log.warn("[无人船SSE] 连接超时: session={}, deviceSn={}", sessionId, deviceSn);
|
||||||
|
removeEmitter(sessionId, deviceSn);
|
||||||
|
});
|
||||||
|
emitter.onError(ex -> {
|
||||||
|
log.error("[无人船SSE] 连接错误: session={}, deviceSn={}, error={}",
|
||||||
|
sessionId, deviceSn, ex.getMessage());
|
||||||
|
removeEmitter(sessionId, deviceSn);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 保存连接
|
||||||
|
EmitterWrapper wrapper = new EmitterWrapper(emitter, 0L, tenantId, sessionId, deviceSn);
|
||||||
|
emitters.put(sessionId, wrapper);
|
||||||
|
|
||||||
|
log.info("[无人船SSE] 新增连接: session={}, deviceSn={}, 当前连接数: {}",
|
||||||
|
sessionId, deviceSn, emitters.size());
|
||||||
|
|
||||||
|
// 发送连接确认
|
||||||
|
try {
|
||||||
|
emitter.send(SseEmitter.event()
|
||||||
|
.name("connected")
|
||||||
|
.data("{\"status\":\"connected\",\"deviceSn\":\"" + deviceSn + "\"}"));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[无人船SSE] 发送连接确认失败: session={}", sessionId, e);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 增加本地引用计数
|
||||||
|
int refCount = deviceRefCount.compute(deviceSn, (k, v) -> v == null ? 1 : v + 1);
|
||||||
|
|
||||||
|
// Redis订阅池: 添加 msg_alarm, online, offline 订阅
|
||||||
|
boolean isFirstMsgAlarm = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.MSG_ALARM);
|
||||||
|
boolean isFirstOnline = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.ONLINE);
|
||||||
|
boolean isFirstOffline = subscriptionPoolService.addSubscription(sessionId, deviceSn, TopicType.OFFLINE);
|
||||||
|
|
||||||
|
// 首次订阅时触发WebSocket订阅
|
||||||
|
if (isFirstOnline || isFirstOffline || isFirstMsgAlarm) {
|
||||||
|
log.info("[无人船SSE] 设备 {} 首次订阅,触发WebSocket懒加载", deviceSn);
|
||||||
|
boatSubscriptionManager.subscribeBoatDevice(deviceSn, tenantId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isFirstMsgAlarm) {
|
||||||
|
log.info("[无人船SSE] 设备 {} 遥测数据首次订阅,订阅msg_alarm并注册回调", deviceSn);
|
||||||
|
boatSubscriptionManager.subscribeBoatTelemetry(deviceSn);
|
||||||
|
|
||||||
|
// 注册 DeviceMessageHandler 的 msgAlarm 回调
|
||||||
|
messageHandler.registerMsgAlarmCallback(deviceSn, (sn, data) -> {
|
||||||
|
sendBoatDataUpdate(sn, data);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
log.info("[无人船SSE] 设备 {} 已有其他订阅者,复用WebSocket订阅, 本地引用: {}", deviceSn, refCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
return emitter;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 移除SSE连接(减少引用计数,必要时取消订阅)
|
||||||
|
*/
|
||||||
|
private void removeEmitter(String sessionId, String deviceSn) {
|
||||||
|
EmitterWrapper wrapper = emitters.remove(sessionId);
|
||||||
|
if (wrapper == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
wrapper.getEmitter().complete();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("[无人船SSE] 完成连接失败(可能已关闭): session={}", sessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("[无人船SSE] 移除连接: session={}, deviceSn={}, 剩余连接数: {}",
|
||||||
|
sessionId, deviceSn, emitters.size());
|
||||||
|
|
||||||
|
// 减少本地引用计数
|
||||||
|
deviceRefCount.compute(deviceSn, (k, v) -> {
|
||||||
|
if (v == null || v <= 1) return null;
|
||||||
|
return v - 1;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Redis订阅池: 移除订阅
|
||||||
|
boolean isLastMsgAlarm = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.MSG_ALARM);
|
||||||
|
boolean isLastOnline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.ONLINE);
|
||||||
|
boolean isLastOffline = subscriptionPoolService.removeSubscription(sessionId, deviceSn, TopicType.OFFLINE);
|
||||||
|
|
||||||
|
// 最后一个msg_alarm订阅者离开 → 取消遥测订阅 + 移除回调
|
||||||
|
if (isLastMsgAlarm) {
|
||||||
|
log.info("[无人船SSE] 设备 {} 最后一个订阅者离开,取消遥测订阅", deviceSn);
|
||||||
|
boatSubscriptionManager.unsubscribeBoatTelemetry(deviceSn);
|
||||||
|
messageHandler.removeMsgAlarmCallback(deviceSn);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 所有基础主题订阅者都离开 → 取消设备订阅
|
||||||
|
if (isLastOnline && isLastOffline) {
|
||||||
|
boolean hasMsgAlarm = subscriptionPoolService.hasSubscribers(deviceSn, TopicType.MSG_ALARM);
|
||||||
|
if (!hasMsgAlarm) {
|
||||||
|
log.info("[无人船SSE] 设备 {} 所有订阅者离开,取消设备订阅", deviceSn);
|
||||||
|
boatSubscriptionManager.unsubscribeBoatDevice(deviceSn);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 主动移除SSE连接(供控制器调用)
|
||||||
|
*/
|
||||||
|
public boolean removeEmitterBySessionId(String sessionId, String deviceSn) {
|
||||||
|
if (!emitters.containsKey(sessionId)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
removeEmitter(sessionId, deviceSn);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 推送无人船数据到所有匹配 deviceSn 的SSE连接
|
||||||
|
*/
|
||||||
|
public void sendBoatDataUpdate(String deviceSn, JSONObject data) {
|
||||||
|
if (data == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> deadEmitters = new ArrayList<>();
|
||||||
|
|
||||||
|
emitters.forEach((sessionId, wrapper) -> {
|
||||||
|
if (deviceSn.equals(wrapper.getDeviceSn())) {
|
||||||
|
try {
|
||||||
|
wrapper.getEmitter().send(SseEmitter.event()
|
||||||
|
.name("boat-telemetry")
|
||||||
|
.data(data.toJSONString())
|
||||||
|
.id("boat-" + System.currentTimeMillis()));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("[无人船SSE] 推送数据失败: session={}, error={}", sessionId, e.getMessage());
|
||||||
|
deadEmitters.add(sessionId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
deadEmitters.forEach(sessionId -> {
|
||||||
|
EmitterWrapper wrapper = emitters.get(sessionId);
|
||||||
|
if (wrapper != null) {
|
||||||
|
removeEmitter(sessionId, wrapper.getDeviceSn());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 心跳(15秒间隔,检测断连)
|
||||||
|
*/
|
||||||
|
private void startHeartbeat() {
|
||||||
|
heartbeatExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||||
|
heartbeatExecutor.scheduleAtFixedRate(() -> {
|
||||||
|
if (emitters.isEmpty()) return;
|
||||||
|
|
||||||
|
List<String> deadEmitters = new ArrayList<>();
|
||||||
|
|
||||||
|
emitters.forEach((sessionId, wrapper) -> {
|
||||||
|
try {
|
||||||
|
wrapper.getEmitter().send(SseEmitter.event()
|
||||||
|
.name("heartbeat")
|
||||||
|
.data("ping"));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("[无人船SSE] 心跳失败: session={}", sessionId);
|
||||||
|
deadEmitters.add(sessionId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!deadEmitters.isEmpty()) {
|
||||||
|
log.info("[无人船SSE] 心跳检测到 {} 个断连,清理", deadEmitters.size());
|
||||||
|
deadEmitters.forEach(sessionId -> {
|
||||||
|
EmitterWrapper wrapper = emitters.get(sessionId);
|
||||||
|
if (wrapper != null) {
|
||||||
|
removeEmitter(sessionId, wrapper.getDeviceSn());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, 15000, 15000, TimeUnit.MILLISECONDS);
|
||||||
|
|
||||||
|
log.info("[无人船SSE] 心跳已启动,间隔: 15秒");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 孤儿订阅清理(30秒间隔)
|
||||||
|
* 检查Redis中记录的session是否还有对应的SSE连接
|
||||||
|
*/
|
||||||
|
private void startOrphanCleanup() {
|
||||||
|
cleanupExecutor = Executors.newSingleThreadScheduledExecutor();
|
||||||
|
cleanupExecutor.scheduleAtFixedRate(() -> {
|
||||||
|
try {
|
||||||
|
java.util.Set<String> activeSessionIds = new java.util.HashSet<>(emitters.keySet());
|
||||||
|
java.util.Set<String> allRedisSessionIds = subscriptionPoolService.getAllSessionIds();
|
||||||
|
|
||||||
|
if (allRedisSessionIds.isEmpty()) return;
|
||||||
|
|
||||||
|
int cleanedCount = 0;
|
||||||
|
for (String sessionId : allRedisSessionIds) {
|
||||||
|
// 只清理无人船的session(boat_前缀)
|
||||||
|
if (!sessionId.startsWith("boat_")) continue;
|
||||||
|
if (activeSessionIds.contains(sessionId)) continue;
|
||||||
|
|
||||||
|
log.info("[无人船SSE] 发现孤儿订阅: sessionId={}", sessionId);
|
||||||
|
|
||||||
|
java.util.List<SubscriptionPoolService.DeviceTopicPair> toUnsubscribe =
|
||||||
|
subscriptionPoolService.removeAllSubscriptions(sessionId);
|
||||||
|
|
||||||
|
for (SubscriptionPoolService.DeviceTopicPair pair : toUnsubscribe) {
|
||||||
|
String deviceSn = pair.getDeviceSn();
|
||||||
|
TopicType topicType = pair.getTopicType();
|
||||||
|
|
||||||
|
if (topicType == TopicType.MSG_ALARM) {
|
||||||
|
if (!subscriptionPoolService.hasSubscribers(deviceSn, TopicType.MSG_ALARM)) {
|
||||||
|
boatSubscriptionManager.unsubscribeBoatTelemetry(deviceSn);
|
||||||
|
messageHandler.removeMsgAlarmCallback(deviceSn);
|
||||||
|
}
|
||||||
|
} else if (topicType == TopicType.ONLINE || topicType == TopicType.OFFLINE) {
|
||||||
|
boolean hasAny = subscriptionPoolService.hasSubscribers(deviceSn, TopicType.MSG_ALARM)
|
||||||
|
|| subscriptionPoolService.hasSubscribers(deviceSn, TopicType.ONLINE)
|
||||||
|
|| subscriptionPoolService.hasSubscribers(deviceSn, TopicType.OFFLINE);
|
||||||
|
if (!hasAny) {
|
||||||
|
boatSubscriptionManager.unsubscribeBoatDevice(deviceSn);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cleanedCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cleanedCount > 0) {
|
||||||
|
log.info("[无人船SSE] 孤儿清理完成: 清理 {} 个session", cleanedCount);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[无人船SSE] 孤儿清理失败: {}", e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}, 30000, 30000, TimeUnit.MILLISECONDS);
|
||||||
|
|
||||||
|
log.info("[无人船SSE] 孤儿清理已启动,间隔: 30秒");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 获取连接数 */
|
||||||
|
public int getConnectionCount() {
|
||||||
|
return emitters.size();
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
-6
@@ -30,26 +30,37 @@ public class BoatCommandController {
|
|||||||
@Parameter(description = "设备SN") @RequestParam String deviceSn,
|
@Parameter(description = "设备SN") @RequestParam String deviceSn,
|
||||||
@Parameter(description = "航线ID") @RequestParam String boatRouteId,
|
@Parameter(description = "航线ID") @RequestParam String boatRouteId,
|
||||||
@Parameter(description = "任务编码") @RequestParam String missionCode) {
|
@Parameter(description = "任务编码") @RequestParam String missionCode) {
|
||||||
String taskId = boatControlService.executeRoute(deviceSn, boatRouteId, missionCode);
|
String commandId = boatControlService.executeRoute(deviceSn, boatRouteId, missionCode);
|
||||||
return Result.succeed(taskId, "任务已下发");
|
return Result.succeed(commandId, "任务已下发");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "暂停航行")
|
@Operation(summary = "暂停航行")
|
||||||
@PostMapping("/pause")
|
@PostMapping("/pause")
|
||||||
public Result<Void> pause(
|
public Result<Void> pause(
|
||||||
@Parameter(description = "设备SN") @RequestParam String deviceSn) {
|
@Parameter(description = "设备SN") @RequestParam String deviceSn,
|
||||||
boatControlService.pause(deviceSn);
|
@Parameter(description = "任务编码") @RequestParam String missionCode) {
|
||||||
|
boatControlService.pause(deviceSn, missionCode);
|
||||||
return Result.succeed(null, "暂停指令已下发");
|
return Result.succeed(null, "暂停指令已下发");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "恢复航行")
|
@Operation(summary = "恢复航行")
|
||||||
@PostMapping("/resume")
|
@PostMapping("/resume")
|
||||||
public Result<Void> resume(
|
public Result<Void> resume(
|
||||||
@Parameter(description = "设备SN") @RequestParam String deviceSn) {
|
@Parameter(description = "设备SN") @RequestParam String deviceSn,
|
||||||
boatControlService.resume(deviceSn);
|
@Parameter(description = "任务编码") @RequestParam String missionCode) {
|
||||||
|
boatControlService.resume(deviceSn, missionCode);
|
||||||
return Result.succeed(null, "恢复指令已下发");
|
return Result.succeed(null, "恢复指令已下发");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "终止任务")
|
||||||
|
@PostMapping("/undo")
|
||||||
|
public Result<Void> undoTask(
|
||||||
|
@Parameter(description = "设备SN") @RequestParam String deviceSn,
|
||||||
|
@Parameter(description = "任务编码") @RequestParam String missionCode) {
|
||||||
|
boatControlService.undoTask(deviceSn, missionCode);
|
||||||
|
return Result.succeed(null, "终止任务指令已下发");
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "返回起点")
|
@Operation(summary = "返回起点")
|
||||||
@PostMapping("/return")
|
@PostMapping("/return")
|
||||||
public Result<Void> returnToStart(
|
public Result<Void> returnToStart(
|
||||||
|
|||||||
+1
-6
@@ -5,7 +5,7 @@ import com.alibaba.nacos.shaded.com.google.gson.Gson;
|
|||||||
import com.alibaba.nacos.shaded.com.google.gson.JsonElement;
|
import com.alibaba.nacos.shaded.com.google.gson.JsonElement;
|
||||||
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
|
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
|
||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
import com.central.device.entity.WaylineRoute;
|
import com.central.device.boat.entity.WaylineRoute;
|
||||||
import com.central.device.feign.FileCenterService;
|
import com.central.device.feign.FileCenterService;
|
||||||
import com.central.device.message.ControlMessageConstant;
|
import com.central.device.message.ControlMessageConstant;
|
||||||
import com.central.device.model.AgeDevice;
|
import com.central.device.model.AgeDevice;
|
||||||
@@ -13,10 +13,8 @@ import com.central.device.model.LineFile;
|
|||||||
import com.central.device.service.IAgeDeviceService;
|
import com.central.device.service.IAgeDeviceService;
|
||||||
import com.central.device.service.ILineFileService;
|
import com.central.device.service.ILineFileService;
|
||||||
import com.central.device.service.IWaylineRouteService;
|
import com.central.device.service.IWaylineRouteService;
|
||||||
import com.central.device.service.LiveStreamService;
|
|
||||||
import com.central.device.util.IotRequestResult;
|
import com.central.device.util.IotRequestResult;
|
||||||
import com.central.device.util.RequestUtils;
|
import com.central.device.util.RequestUtils;
|
||||||
import com.central.device.util.TencentLiveUtil;
|
|
||||||
import com.central.device.websocket.manager.DeviceCommandManager;
|
import com.central.device.websocket.manager.DeviceCommandManager;
|
||||||
import com.central.device.websocket.model.CommandStatus;
|
import com.central.device.websocket.model.CommandStatus;
|
||||||
import com.central.device.websocket.model.DeviceCommand;
|
import com.central.device.websocket.model.DeviceCommand;
|
||||||
@@ -30,10 +28,7 @@ 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.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 设备命令控制器
|
* 设备命令控制器
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.controller;
|
package com.central.device.controller;
|
||||||
|
|
||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
import com.central.device.entity.DroneFlightTrack;
|
import com.central.device.boat.entity.DroneFlightTrack;
|
||||||
import com.central.device.model.vo.FlightTrackVO;
|
import com.central.device.model.vo.FlightTrackVO;
|
||||||
import com.central.device.service.IDroneFlightTrackService;
|
import com.central.device.service.IDroneFlightTrackService;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.controller;
|
package com.central.device.controller;
|
||||||
|
|
||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
import com.central.device.entity.WaterBoundary;
|
import com.central.device.boat.entity.WaterBoundary;
|
||||||
import com.central.device.model.dto.PointDTO;
|
import com.central.device.model.dto.PointDTO;
|
||||||
import com.central.device.model.dto.WaterBoundaryCreateDTO;
|
import com.central.device.model.dto.WaterBoundaryCreateDTO;
|
||||||
import com.central.device.model.dto.WaterBoundaryDisplayUpdateDTO;
|
import com.central.device.model.dto.WaterBoundaryDisplayUpdateDTO;
|
||||||
|
|||||||
+3
-3
@@ -1,9 +1,9 @@
|
|||||||
package com.central.device.controller;
|
package com.central.device.controller;
|
||||||
|
|
||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
import com.central.device.entity.WaylineAction;
|
import com.central.device.boat.entity.WaylineAction;
|
||||||
import com.central.device.entity.WaylineRoute;
|
import com.central.device.boat.entity.WaylineRoute;
|
||||||
import com.central.device.entity.WaylineWaypoint;
|
import com.central.device.boat.entity.WaylineWaypoint;
|
||||||
import com.central.device.model.dto.WaylineRouteCreateDTO;
|
import com.central.device.model.dto.WaylineRouteCreateDTO;
|
||||||
import com.central.device.model.dto.BindDeviceDTO;
|
import com.central.device.model.dto.BindDeviceDTO;
|
||||||
import com.central.device.model.vo.WaylineRouteVO;
|
import com.central.device.model.vo.WaylineRouteVO;
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.mapper;
|
package com.central.device.mapper;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
import com.central.device.entity.BoatRoute;
|
import com.central.device.boat.entity.BoatRoute;
|
||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.mapper;
|
package com.central.device.mapper;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
import com.central.device.entity.BoatTrack;
|
import com.central.device.boat.entity.BoatTrack;
|
||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.mapper;
|
package com.central.device.mapper;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
import com.central.device.entity.BoatWaypoint;
|
import com.central.device.boat.entity.BoatWaypoint;
|
||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.mapper;
|
package com.central.device.mapper;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
import com.central.device.entity.DroneFlightTrack;
|
import com.central.device.boat.entity.DroneFlightTrack;
|
||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.mapper;
|
package com.central.device.mapper;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
import com.central.device.entity.WaterBoundary;
|
import com.central.device.boat.entity.WaterBoundary;
|
||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.mapper;
|
package com.central.device.mapper;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
import com.central.device.entity.WaylineAction;
|
import com.central.device.boat.entity.WaylineAction;
|
||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.mapper;
|
package com.central.device.mapper;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
import com.central.device.entity.WaylineRoute;
|
import com.central.device.boat.entity.WaylineRoute;
|
||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.mapper;
|
package com.central.device.mapper;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
import com.central.device.entity.WaylineWaypoint;
|
import com.central.device.boat.entity.WaylineWaypoint;
|
||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
|||||||
+2
-1
@@ -13,7 +13,8 @@ public enum ControlEnum {
|
|||||||
FLY_TO_POINT_UPDATE("fly_to_point_stop"),
|
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"),
|
||||||
|
FLIGHTTASK_UNDO("flighttask_undo");
|
||||||
|
|
||||||
private final String name;
|
private final String name;
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
package com.central.device.model.vo;
|
package com.central.device.model.vo;
|
||||||
|
|
||||||
import com.central.device.entity.BoatWaypoint;
|
import com.central.device.boat.entity.BoatWaypoint;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
||||||
|
|||||||
+13
-3
@@ -16,7 +16,7 @@ public interface IBoatControlService {
|
|||||||
* @param deviceSn 设备SN
|
* @param deviceSn 设备SN
|
||||||
* @param boatRouteId 航线ID
|
* @param boatRouteId 航线ID
|
||||||
* @param missionCode 任务编码
|
* @param missionCode 任务编码
|
||||||
* @return 任务ID
|
* @return 命令ID
|
||||||
*/
|
*/
|
||||||
String executeRoute(String deviceSn, String boatRouteId, String missionCode);
|
String executeRoute(String deviceSn, String boatRouteId, String missionCode);
|
||||||
|
|
||||||
@@ -24,15 +24,25 @@ public interface IBoatControlService {
|
|||||||
* 暂停航行
|
* 暂停航行
|
||||||
*
|
*
|
||||||
* @param deviceSn 设备SN
|
* @param deviceSn 设备SN
|
||||||
|
* @param missionCode 任务编码(对应 order_no)
|
||||||
*/
|
*/
|
||||||
void pause(String deviceSn);
|
void pause(String deviceSn, String missionCode);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 恢复航行
|
* 恢复航行
|
||||||
*
|
*
|
||||||
* @param deviceSn 设备SN
|
* @param deviceSn 设备SN
|
||||||
|
* @param missionCode 任务编码(对应 order_no)
|
||||||
*/
|
*/
|
||||||
void resume(String deviceSn);
|
void resume(String deviceSn, String missionCode);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 终止任务(结束航行)
|
||||||
|
*
|
||||||
|
* @param deviceSn 设备SN
|
||||||
|
* @param missionCode 任务编码(对应 order_no)
|
||||||
|
*/
|
||||||
|
void undoTask(String deviceSn, String missionCode);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 返回起点
|
* 返回起点
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@ package com.central.device.service;
|
|||||||
|
|
||||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
import com.baomidou.mybatisplus.extension.service.IService;
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
import com.central.device.entity.BoatRoute;
|
import com.central.device.boat.entity.BoatRoute;
|
||||||
import com.central.device.model.dto.BoatRouteCreateDTO;
|
import com.central.device.model.dto.BoatRouteCreateDTO;
|
||||||
import com.central.device.model.dto.BoatRouteUpdateDTO;
|
import com.central.device.model.dto.BoatRouteUpdateDTO;
|
||||||
import com.central.device.model.vo.BoatRouteDetailVO;
|
import com.central.device.model.vo.BoatRouteDetailVO;
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.service;
|
package com.central.device.service;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.extension.service.IService;
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
import com.central.device.entity.BoatTrack;
|
import com.central.device.boat.entity.BoatTrack;
|
||||||
import com.central.device.model.vo.BoatRealtimeVO;
|
import com.central.device.model.vo.BoatRealtimeVO;
|
||||||
import com.central.device.model.vo.TaskTrackVO;
|
import com.central.device.model.vo.TaskTrackVO;
|
||||||
import com.central.device.model.vo.TrackPointVO;
|
import com.central.device.model.vo.TrackPointVO;
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.service;
|
package com.central.device.service;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.extension.service.IService;
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
import com.central.device.entity.DroneFlightTrack;
|
import com.central.device.boat.entity.DroneFlightTrack;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.service;
|
package com.central.device.service;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.extension.service.IService;
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
import com.central.device.entity.WaterBoundary;
|
import com.central.device.boat.entity.WaterBoundary;
|
||||||
import com.central.device.model.dto.PointDTO;
|
import com.central.device.model.dto.PointDTO;
|
||||||
import com.central.device.model.dto.WaterBoundaryCreateDTO;
|
import com.central.device.model.dto.WaterBoundaryCreateDTO;
|
||||||
import com.central.device.model.vo.BoundaryCheckResultVO;
|
import com.central.device.model.vo.BoundaryCheckResultVO;
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.service;
|
package com.central.device.service;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.extension.service.IService;
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
import com.central.device.entity.WaylineRoute;
|
import com.central.device.boat.entity.WaylineRoute;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.service;
|
package com.central.device.service;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.extension.service.IService;
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
import com.central.device.entity.WaylineWaypoint;
|
import com.central.device.boat.entity.WaylineWaypoint;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
|||||||
+63
-191
@@ -1,21 +1,21 @@
|
|||||||
package com.central.device.service.impl;
|
package com.central.device.service.impl;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSONObject;
|
||||||
import com.central.common.exception.BusinessException;
|
import com.central.common.exception.BusinessException;
|
||||||
import com.central.device.entity.BoatRoute;
|
import com.central.device.boat.entity.BoatRoute;
|
||||||
|
import com.central.device.boat.manager.BoatCommandManager;
|
||||||
|
import com.central.device.model.AgeDevice;
|
||||||
import com.central.device.model.dto.BoatManualControlDTO;
|
import com.central.device.model.dto.BoatManualControlDTO;
|
||||||
|
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;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.UUID;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 无人船控制服务实现
|
* 无人船控制服务实现
|
||||||
* 当前为Mock实现,待实际设备对接后替换
|
* 通过 BoatCommandManager 向 JetLinks IoT 平台下发真实控制指令
|
||||||
*
|
*
|
||||||
* @author dzc
|
* @author dzc
|
||||||
* @date 2026-01-05
|
* @date 2026-01-05
|
||||||
@@ -26,240 +26,112 @@ import java.util.concurrent.ConcurrentHashMap;
|
|||||||
public class BoatControlServiceImpl implements IBoatControlService {
|
public class BoatControlServiceImpl implements IBoatControlService {
|
||||||
|
|
||||||
private final IBoatRouteService boatRouteService;
|
private final IBoatRouteService boatRouteService;
|
||||||
|
private final BoatCommandManager boatCommandManager;
|
||||||
/**
|
private final IAgeDeviceService ageDeviceService;
|
||||||
* Mock设备状态存储
|
|
||||||
* key: deviceSn, value: status
|
|
||||||
*/
|
|
||||||
private final Map<String, DeviceState> deviceStates = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Mock设备状态
|
|
||||||
*/
|
|
||||||
private static class DeviceState {
|
|
||||||
String status = "idle"; // idle, executing, paused, returning, stopped
|
|
||||||
String currentTaskId;
|
|
||||||
String currentRouteId;
|
|
||||||
boolean online = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String executeRoute(String deviceSn, String boatRouteId, String missionCode) {
|
public String executeRoute(String deviceSn, String boatRouteId, String missionCode) {
|
||||||
log.info("[Mock] 执行航线任务: deviceSn={}, routeId={}, missionCode={}", deviceSn, boatRouteId, missionCode);
|
log.info("无人船执行航线任务: deviceSn={}, routeId={}, missionCode={}", deviceSn, boatRouteId, missionCode);
|
||||||
|
|
||||||
// 验证航线
|
// 1. 验证航线
|
||||||
BoatRoute route = boatRouteService.getByRouteId(boatRouteId);
|
BoatRoute route = boatRouteService.getByRouteId(boatRouteId);
|
||||||
if (route == null) {
|
if (route == null) {
|
||||||
throw new BusinessException("航线不存在");
|
throw new BusinessException("航线不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查设备状态
|
// 2. 构建指令参数
|
||||||
DeviceState state = getOrCreateDeviceState(deviceSn);
|
JSONObject params = new JSONObject();
|
||||||
if (!state.online) {
|
params.put("order_no", missionCode);
|
||||||
throw new BusinessException("设备离线");
|
params.put("wayline_link_url", route.getRouteFileUrl());
|
||||||
}
|
params.put("file_md5", "");
|
||||||
if ("executing".equals(state.status)) {
|
params.put("stream_urls", getStreamUrls(deviceSn));
|
||||||
throw new BusinessException("设备正在执行其他任务");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 生成任务ID
|
// 3. 通过 WebSocket 下发指令
|
||||||
String taskId = UUID.randomUUID().toString().replace("-", "");
|
String commandId = boatCommandManager.sendCommand(deviceSn, "flighttask_prepare", params);
|
||||||
|
|
||||||
// 更新Mock状态
|
// 4. 更新航线状态
|
||||||
state.status = "executing";
|
|
||||||
state.currentTaskId = taskId;
|
|
||||||
state.currentRouteId = boatRouteId;
|
|
||||||
|
|
||||||
// 更新航线状态
|
|
||||||
boatRouteService.updateStatus(boatRouteId, BoatRoute.RouteStatus.EXECUTING.getCode());
|
boatRouteService.updateStatus(boatRouteId, BoatRoute.RouteStatus.EXECUTING.getCode());
|
||||||
|
|
||||||
// TODO: 实际设备对接时,通过MQTT/WebSocket发送控制指令
|
log.info("无人船航线任务已下发: commandId={}, missionCode={}", commandId, missionCode);
|
||||||
// 指令格式示例:
|
return commandId;
|
||||||
// {
|
|
||||||
// "cmd": "execute_route",
|
|
||||||
// "taskId": taskId,
|
|
||||||
// "routeId": boatRouteId,
|
|
||||||
// "waypoints": [...],
|
|
||||||
// "params": { "speed": ..., "loop": ... }
|
|
||||||
// }
|
|
||||||
|
|
||||||
log.info("[Mock] 航线任务已下发: taskId={}", taskId);
|
|
||||||
return taskId;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void pause(String deviceSn) {
|
public void pause(String deviceSn, String missionCode) {
|
||||||
log.info("[Mock] 暂停航行: deviceSn={}", deviceSn);
|
log.info("无人船暂停任务: deviceSn={}, missionCode={}", deviceSn, missionCode);
|
||||||
|
|
||||||
DeviceState state = getOrCreateDeviceState(deviceSn);
|
JSONObject params = new JSONObject();
|
||||||
if (!"executing".equals(state.status)) {
|
params.put("order_no", missionCode);
|
||||||
throw new BusinessException("设备当前未在执行任务");
|
|
||||||
}
|
|
||||||
|
|
||||||
state.status = "paused";
|
boatCommandManager.sendCommand(deviceSn, "flighttask_pause", params);
|
||||||
|
|
||||||
// TODO: 发送暂停指令到设备
|
|
||||||
// {
|
|
||||||
// "cmd": "pause",
|
|
||||||
// "deviceSn": deviceSn
|
|
||||||
// }
|
|
||||||
|
|
||||||
log.info("[Mock] 暂停指令已下发");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void resume(String deviceSn) {
|
public void resume(String deviceSn, String missionCode) {
|
||||||
log.info("[Mock] 恢复航行: deviceSn={}", deviceSn);
|
log.info("无人船恢复任务: deviceSn={}, missionCode={}", deviceSn, missionCode);
|
||||||
|
|
||||||
DeviceState state = getOrCreateDeviceState(deviceSn);
|
JSONObject params = new JSONObject();
|
||||||
if (!"paused".equals(state.status)) {
|
params.put("order_no", missionCode);
|
||||||
throw new BusinessException("设备当前未处于暂停状态");
|
|
||||||
}
|
|
||||||
|
|
||||||
state.status = "executing";
|
boatCommandManager.sendCommand(deviceSn, "flighttask_recovery", params);
|
||||||
|
}
|
||||||
|
|
||||||
// TODO: 发送恢复指令到设备
|
@Override
|
||||||
// {
|
public void undoTask(String deviceSn, String missionCode) {
|
||||||
// "cmd": "resume",
|
log.info("无人船终止任务: deviceSn={}, missionCode={}", deviceSn, missionCode);
|
||||||
// "deviceSn": deviceSn
|
|
||||||
// }
|
|
||||||
|
|
||||||
log.info("[Mock] 恢复指令已下发");
|
JSONObject params = new JSONObject();
|
||||||
|
params.put("order_no", missionCode);
|
||||||
|
|
||||||
|
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", params);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void returnToStart(String deviceSn) {
|
public void returnToStart(String deviceSn) {
|
||||||
log.info("[Mock] 返回起点: deviceSn={}", deviceSn);
|
log.info("无人船返回起点: deviceSn={}", deviceSn);
|
||||||
|
// 返回起点等同于终止当前任务,设备端自行处理返航逻辑
|
||||||
DeviceState state = getOrCreateDeviceState(deviceSn);
|
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", new JSONObject());
|
||||||
if (!state.online) {
|
|
||||||
throw new BusinessException("设备离线");
|
|
||||||
}
|
|
||||||
|
|
||||||
String previousStatus = state.status;
|
|
||||||
state.status = "returning";
|
|
||||||
|
|
||||||
// 如果有正在执行的航线,更新状态
|
|
||||||
if (state.currentRouteId != null && "executing".equals(previousStatus)) {
|
|
||||||
boatRouteService.updateStatus(state.currentRouteId, BoatRoute.RouteStatus.PUBLISHED.getCode());
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: 发送返航指令到设备
|
|
||||||
// {
|
|
||||||
// "cmd": "return_to_start",
|
|
||||||
// "deviceSn": deviceSn
|
|
||||||
// }
|
|
||||||
|
|
||||||
log.info("[Mock] 返航指令已下发");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void emergencyStop(String deviceSn) {
|
public void emergencyStop(String deviceSn) {
|
||||||
log.warn("[Mock] 紧急停止: deviceSn={}", deviceSn);
|
log.warn("无人船紧急停止: deviceSn={}", deviceSn);
|
||||||
|
// 紧急停止使用终止任务指令
|
||||||
DeviceState state = getOrCreateDeviceState(deviceSn);
|
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", new JSONObject());
|
||||||
|
|
||||||
String previousRouteId = state.currentRouteId;
|
|
||||||
state.status = "stopped";
|
|
||||||
state.currentTaskId = null;
|
|
||||||
state.currentRouteId = null;
|
|
||||||
|
|
||||||
// 更新航线状态
|
|
||||||
if (previousRouteId != null) {
|
|
||||||
boatRouteService.updateStatus(previousRouteId, BoatRoute.RouteStatus.PUBLISHED.getCode());
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: 发送紧急停止指令到设备(最高优先级)
|
|
||||||
// {
|
|
||||||
// "cmd": "emergency_stop",
|
|
||||||
// "deviceSn": deviceSn,
|
|
||||||
// "priority": "highest"
|
|
||||||
// }
|
|
||||||
|
|
||||||
log.warn("[Mock] 紧急停止指令已下发");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void manualControl(String deviceSn, BoatManualControlDTO dto) {
|
public void manualControl(String deviceSn, BoatManualControlDTO dto) {
|
||||||
log.debug("[Mock] 手动控制: deviceSn={}, throttle={}, rudder={}",
|
log.debug("无人船手动控制: deviceSn={}, throttle={}, rudder={}",
|
||||||
deviceSn, dto.getThrottle(), dto.getRudder());
|
deviceSn, dto.getThrottle(), dto.getRudder());
|
||||||
|
// 手动控制暂不通过此链路实现,保留接口
|
||||||
DeviceState state = getOrCreateDeviceState(deviceSn);
|
// TODO: 如有专用手动控制协议,后续对接
|
||||||
if (!state.online) {
|
|
||||||
throw new BusinessException("设备离线");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 手动控制时暂停自动任务
|
|
||||||
if ("executing".equals(state.status)) {
|
|
||||||
state.status = "paused";
|
|
||||||
log.info("[Mock] 切换到手动控制模式,自动任务已暂停");
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: 发送手动控制指令到设备
|
|
||||||
// 这类指令需要高频发送(如50ms间隔)
|
|
||||||
// {
|
|
||||||
// "cmd": "manual_control",
|
|
||||||
// "deviceSn": deviceSn,
|
|
||||||
// "throttle": dto.getThrottle(),
|
|
||||||
// "rudder": dto.getRudder(),
|
|
||||||
// "timestamp": System.currentTimeMillis()
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isDeviceOnline(String deviceSn) {
|
public boolean isDeviceOnline(String deviceSn) {
|
||||||
DeviceState state = deviceStates.get(deviceSn);
|
// TODO: 后续对接真实设备在线状态查询
|
||||||
if (state == null) {
|
return true;
|
||||||
// Mock: 假设首次查询的设备都在线
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return state.online;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getDeviceStatus(String deviceSn) {
|
public String getDeviceStatus(String deviceSn) {
|
||||||
DeviceState state = deviceStates.get(deviceSn);
|
// TODO: 后续对接真实设备状态查询
|
||||||
if (state == null) {
|
return "idle";
|
||||||
return "idle";
|
|
||||||
}
|
|
||||||
return state.status;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ========== Mock辅助方法 ==========
|
|
||||||
|
|
||||||
private DeviceState getOrCreateDeviceState(String deviceSn) {
|
|
||||||
return deviceStates.computeIfAbsent(deviceSn, k -> new DeviceState());
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 模拟设备上线(供测试使用)
|
|
||||||
*/
|
|
||||||
public void mockDeviceOnline(String deviceSn) {
|
|
||||||
DeviceState state = getOrCreateDeviceState(deviceSn);
|
|
||||||
state.online = true;
|
|
||||||
log.info("[Mock] 设备上线: deviceSn={}", deviceSn);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 模拟设备离线(供测试使用)
|
|
||||||
*/
|
|
||||||
public void mockDeviceOffline(String deviceSn) {
|
|
||||||
DeviceState state = getOrCreateDeviceState(deviceSn);
|
|
||||||
state.online = false;
|
|
||||||
log.info("[Mock] 设备离线: deviceSn={}", deviceSn);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 模拟任务完成(供测试使用)
|
* 获取设备视频流地址
|
||||||
*/
|
*/
|
||||||
public void mockTaskComplete(String deviceSn) {
|
private JSONObject getStreamUrls(String deviceSn) {
|
||||||
DeviceState state = deviceStates.get(deviceSn);
|
JSONObject result = new JSONObject();
|
||||||
if (state != null && state.currentRouteId != null) {
|
AgeDevice device = ageDeviceService.getByDeviceSn(deviceSn);
|
||||||
boatRouteService.updateStatus(state.currentRouteId, BoatRoute.RouteStatus.PUBLISHED.getCode());
|
if (device != null) {
|
||||||
state.status = "idle";
|
result.put("pushUrl", device.getPushStreamUrl());
|
||||||
state.currentTaskId = null;
|
|
||||||
state.currentRouteId = null;
|
|
||||||
log.info("[Mock] 任务完成: deviceSn={}", deviceSn);
|
|
||||||
}
|
}
|
||||||
|
result.put("playRtmpUrl", "");
|
||||||
|
result.put("playFlvUrl", "");
|
||||||
|
result.put("playM3u8Url", "");
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -7,8 +7,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
|||||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
import com.central.common.context.LoginUserContextHolder;
|
import com.central.common.context.LoginUserContextHolder;
|
||||||
import com.central.common.exception.BusinessException;
|
import com.central.common.exception.BusinessException;
|
||||||
import com.central.device.entity.BoatRoute;
|
import com.central.device.boat.entity.BoatRoute;
|
||||||
import com.central.device.entity.BoatWaypoint;
|
import com.central.device.boat.entity.BoatWaypoint;
|
||||||
import com.central.device.feign.FileCenterService;
|
import com.central.device.feign.FileCenterService;
|
||||||
import com.central.device.mapper.BoatRouteMapper;
|
import com.central.device.mapper.BoatRouteMapper;
|
||||||
import com.central.device.mapper.BoatWaypointMapper;
|
import com.central.device.mapper.BoatWaypointMapper;
|
||||||
@@ -80,7 +80,7 @@ public class BoatRouteServiceImpl extends ServiceImpl<BoatRouteMapper, BoatRoute
|
|||||||
} catch (Exception ignored) {
|
} catch (Exception ignored) {
|
||||||
log.error("获取当前登录用户租户失败");
|
log.error("获取当前登录用户租户失败");
|
||||||
}
|
}
|
||||||
route.setTenantId(anchor);
|
route.setTenantId(anchor==null?"webApp":anchor);
|
||||||
route.setStatus(BoatRoute.RouteStatus.DRAFT.getCode());
|
route.setStatus(BoatRoute.RouteStatus.DRAFT.getCode());
|
||||||
route.setIsTemplate(false);
|
route.setIsTemplate(false);
|
||||||
route.setShowInModel(dto.getShowInModel() != null ? dto.getShowInModel() : 0);
|
route.setShowInModel(dto.getShowInModel() != null ? dto.getShowInModel() : 0);
|
||||||
|
|||||||
+1
-3
@@ -1,9 +1,8 @@
|
|||||||
package com.central.device.service.impl;
|
package com.central.device.service.impl;
|
||||||
|
|
||||||
import cn.hutool.core.bean.BeanUtil;
|
|
||||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
import com.central.common.exception.BusinessException;
|
import com.central.common.exception.BusinessException;
|
||||||
import com.central.device.entity.BoatTrack;
|
import com.central.device.boat.entity.BoatTrack;
|
||||||
import com.central.device.mapper.BoatTrackMapper;
|
import com.central.device.mapper.BoatTrackMapper;
|
||||||
import com.central.device.model.vo.BoatRealtimeVO;
|
import com.central.device.model.vo.BoatRealtimeVO;
|
||||||
import com.central.device.model.vo.TaskTrackVO;
|
import com.central.device.model.vo.TaskTrackVO;
|
||||||
@@ -14,7 +13,6 @@ import lombok.extern.slf4j.Slf4j;
|
|||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|||||||
+1
-2
@@ -1,13 +1,12 @@
|
|||||||
package com.central.device.service.impl;
|
package com.central.device.service.impl;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
import com.central.device.entity.DroneFlightTrack;
|
import com.central.device.boat.entity.DroneFlightTrack;
|
||||||
import com.central.device.mapper.DroneFlightTrackMapper;
|
import com.central.device.mapper.DroneFlightTrackMapper;
|
||||||
import com.central.device.service.IDroneFlightTrackService;
|
import com.central.device.service.IDroneFlightTrackService;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
|||||||
+1
-2
@@ -8,7 +8,7 @@ import com.alibaba.fastjson.JSONObject;
|
|||||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
import com.central.common.context.LoginUserContextHolder;
|
import com.central.common.context.LoginUserContextHolder;
|
||||||
import com.central.common.exception.BusinessException;
|
import com.central.common.exception.BusinessException;
|
||||||
import com.central.device.entity.WaterBoundary;
|
import com.central.device.boat.entity.WaterBoundary;
|
||||||
import com.central.device.mapper.WaterBoundaryMapper;
|
import com.central.device.mapper.WaterBoundaryMapper;
|
||||||
import com.central.device.model.dto.PointDTO;
|
import com.central.device.model.dto.PointDTO;
|
||||||
import com.central.device.model.dto.WaterBoundaryCreateDTO;
|
import com.central.device.model.dto.WaterBoundaryCreateDTO;
|
||||||
@@ -21,7 +21,6 @@ import org.springframework.scheduling.annotation.Async;
|
|||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|||||||
+3
-3
@@ -1,8 +1,8 @@
|
|||||||
package com.central.device.service.impl;
|
package com.central.device.service.impl;
|
||||||
|
|
||||||
import com.central.device.entity.WaylineAction;
|
import com.central.device.boat.entity.WaylineAction;
|
||||||
import com.central.device.entity.WaylineRoute;
|
import com.central.device.boat.entity.WaylineRoute;
|
||||||
import com.central.device.entity.WaylineWaypoint;
|
import com.central.device.boat.entity.WaylineWaypoint;
|
||||||
import com.central.device.feign.FileCenterService;
|
import com.central.device.feign.FileCenterService;
|
||||||
import com.central.device.mapper.WaylineActionMapper;
|
import com.central.device.mapper.WaylineActionMapper;
|
||||||
import com.central.device.mapper.WaylineRouteMapper;
|
import com.central.device.mapper.WaylineRouteMapper;
|
||||||
|
|||||||
+1
-3
@@ -1,13 +1,12 @@
|
|||||||
package com.central.device.service.impl;
|
package com.central.device.service.impl;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
import com.central.device.entity.WaylineRoute;
|
import com.central.device.boat.entity.WaylineRoute;
|
||||||
import com.central.device.mapper.WaylineRouteMapper;
|
import com.central.device.mapper.WaylineRouteMapper;
|
||||||
import com.central.device.mapper.WaylineActionMapper;
|
import com.central.device.mapper.WaylineActionMapper;
|
||||||
import com.central.device.mapper.WaylineWaypointMapper;
|
import com.central.device.mapper.WaylineWaypointMapper;
|
||||||
import com.central.device.mapper.DroneFlightTrackMapper;
|
import com.central.device.mapper.DroneFlightTrackMapper;
|
||||||
import com.central.device.service.IWaylineRouteService;
|
import com.central.device.service.IWaylineRouteService;
|
||||||
import com.central.device.model.LineFile;
|
|
||||||
import com.central.device.service.IWaylineParseService;
|
import com.central.device.service.IWaylineParseService;
|
||||||
import com.central.device.parser.model.KmzParseResult;
|
import com.central.device.parser.model.KmzParseResult;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
@@ -17,7 +16,6 @@ import org.springframework.transaction.annotation.Transactional;
|
|||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package com.central.device.service.impl;
|
package com.central.device.service.impl;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
import com.central.device.entity.WaylineWaypoint;
|
import com.central.device.boat.entity.WaylineWaypoint;
|
||||||
import com.central.device.mapper.WaylineWaypointMapper;
|
import com.central.device.mapper.WaylineWaypointMapper;
|
||||||
import com.central.device.service.IWaylineWaypointService;
|
import com.central.device.service.IWaylineWaypointService;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|||||||
+34
-146
@@ -1,9 +1,7 @@
|
|||||||
package com.central.device.sse.controller;
|
package com.central.device.sse.controller;
|
||||||
|
|
||||||
import com.alibaba.fastjson.JSON;
|
|
||||||
import com.central.common.context.LoginUserContextHolder;
|
import com.central.common.context.LoginUserContextHolder;
|
||||||
import com.central.device.model.vo.BoatRealtimeVO;
|
import com.central.device.boat.sse.BoatSseEmitterManager;
|
||||||
import com.central.device.service.IBoatTrackService;
|
|
||||||
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;
|
||||||
@@ -14,14 +12,16 @@ import org.springframework.http.ResponseEntity;
|
|||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 无人船遥测数据SSE控制器
|
* 无人船遥测数据SSE控制器
|
||||||
* 提供SSE端点供前端订阅无人船实时位置数据
|
* 提供SSE端点供前端订阅无人船实时数据
|
||||||
|
*
|
||||||
|
* 数据流:
|
||||||
|
* JetLinks IoT → WebSocket → DeviceMessageHandler → msgAlarmCallback
|
||||||
|
* → BoatSseEmitterManager → SSE推送到前端
|
||||||
*
|
*
|
||||||
* @author dzc
|
* @author dzc
|
||||||
* @date 2026-01-05
|
* @date 2026-01-05
|
||||||
@@ -33,17 +33,11 @@ import java.util.concurrent.ConcurrentHashMap;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class BoatTelemetrySseController {
|
public class BoatTelemetrySseController {
|
||||||
|
|
||||||
private final IBoatTrackService boatTrackService;
|
private final BoatSseEmitterManager boatSseEmitterManager;
|
||||||
|
|
||||||
/**
|
|
||||||
* 存储SSE连接
|
|
||||||
* key: connectionId, value: SseEmitter
|
|
||||||
*/
|
|
||||||
private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 订阅无人船遥测数据SSE连接
|
* 订阅无人船遥测数据SSE连接
|
||||||
* 前端建立SSE连接后,会实时推送无人船位置、速度、电量等数据
|
* 前端建立SSE连接后,后端自动触发WebSocket订阅并实时推送无人船数据
|
||||||
*
|
*
|
||||||
* @param deviceSn 设备SN
|
* @param deviceSn 设备SN
|
||||||
* @param clientSessionId 客户端会话ID(可选)
|
* @param clientSessionId 客户端会话ID(可选)
|
||||||
@@ -58,83 +52,33 @@ public class BoatTelemetrySseController {
|
|||||||
@RequestHeader(value = "X-Client-Session-Id", required = false) String clientSessionId) {
|
@RequestHeader(value = "X-Client-Session-Id", required = false) String clientSessionId) {
|
||||||
|
|
||||||
String tenantId = LoginUserContextHolder.getCurrentTenantId() != null
|
String tenantId = LoginUserContextHolder.getCurrentTenantId() != null
|
||||||
? LoginUserContextHolder.getCurrentTenantId() : "1";
|
? LoginUserContextHolder.getCurrentTenantId() : "1";
|
||||||
String username = LoginUserContextHolder.getUser() != null
|
String username = LoginUserContextHolder.getUser() != null
|
||||||
? LoginUserContextHolder.getUser().getUsername() : "anonymous";
|
? LoginUserContextHolder.getUser().getUsername() : "anonymous";
|
||||||
|
|
||||||
// 生成connectionId
|
String sessionId;
|
||||||
String connectionId;
|
|
||||||
if (clientSessionId != null && !clientSessionId.trim().isEmpty()) {
|
if (clientSessionId != null && !clientSessionId.trim().isEmpty()) {
|
||||||
connectionId = "boat_" + clientSessionId + "_" + deviceSn;
|
sessionId = "boat_" + clientSessionId + "_" + deviceSn;
|
||||||
log.info("客户端订阅无人船遥测SSE(复用会话): connectionId={}, deviceSn={}, tenant={}, user={}",
|
log.info("[无人船SSE] 客户端订阅(复用会话): session={}, deviceSn={}, tenant={}, user={}",
|
||||||
connectionId, deviceSn, tenantId, username);
|
sessionId, deviceSn, tenantId, username);
|
||||||
} else {
|
} else {
|
||||||
connectionId = "boat_" + UUID.randomUUID().toString() + "_" + deviceSn;
|
sessionId = "boat_" + UUID.randomUUID() + "_" + deviceSn;
|
||||||
log.info("客户端订阅无人船遥测SSE(新会话): connectionId={}, deviceSn={}, tenant={}, user={}",
|
log.info("[无人船SSE] 客户端订阅(新会话): session={}, deviceSn={}, tenant={}, user={}",
|
||||||
connectionId, deviceSn, tenantId, username);
|
sessionId, deviceSn, tenantId, username);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果已存在相同连接,先移除
|
SseEmitter emitter = boatSseEmitterManager.addEmitter(sessionId, deviceSn, tenantId);
|
||||||
if (emitters.containsKey(connectionId)) {
|
|
||||||
removeConnection(connectionId, deviceSn);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 创建SSE连接 (30分钟超时)
|
|
||||||
SseEmitter emitter = new SseEmitter(30 * 60 * 1000L);
|
|
||||||
|
|
||||||
// 配置回调
|
|
||||||
emitter.onCompletion(() -> {
|
|
||||||
log.info("无人船SSE连接完成: connectionId={}", connectionId);
|
|
||||||
removeConnection(connectionId, deviceSn);
|
|
||||||
});
|
|
||||||
|
|
||||||
emitter.onTimeout(() -> {
|
|
||||||
log.info("无人船SSE连接超时: connectionId={}", connectionId);
|
|
||||||
removeConnection(connectionId, deviceSn);
|
|
||||||
});
|
|
||||||
|
|
||||||
emitter.onError(e -> {
|
|
||||||
log.warn("无人船SSE连接错误: connectionId={}, error={}", connectionId, e.getMessage());
|
|
||||||
removeConnection(connectionId, deviceSn);
|
|
||||||
});
|
|
||||||
|
|
||||||
// 存储连接
|
|
||||||
emitters.put(connectionId, emitter);
|
|
||||||
|
|
||||||
// 注册遥测数据回调
|
|
||||||
boatTrackService.registerTelemetryCallback(deviceSn, connectionId, data -> {
|
|
||||||
sendTelemetryData(connectionId, data);
|
|
||||||
});
|
|
||||||
|
|
||||||
// 发送初始连接成功事件
|
|
||||||
try {
|
|
||||||
emitter.send(SseEmitter.event()
|
|
||||||
.name("connected")
|
|
||||||
.data("{\"status\":\"connected\",\"deviceSn\":\"" + deviceSn + "\"}"));
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.error("发送初始连接事件失败: connectionId={}", connectionId, e);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 发送当前实时位置(如果有)
|
|
||||||
BoatRealtimeVO realtime = boatTrackService.getRealtimePosition(deviceSn);
|
|
||||||
if (realtime != null) {
|
|
||||||
sendTelemetryData(connectionId, realtime);
|
|
||||||
}
|
|
||||||
|
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.header("Cache-Control", "no-cache, no-transform")
|
.header("Cache-Control", "no-cache, no-transform")
|
||||||
.header("Connection", "keep-alive")
|
.header("Connection", "keep-alive")
|
||||||
.header("X-Accel-Buffering", "no")
|
.header("X-Accel-Buffering", "no")
|
||||||
.contentType(MediaType.TEXT_EVENT_STREAM)
|
.contentType(MediaType.TEXT_EVENT_STREAM)
|
||||||
.body(emitter);
|
.body(emitter);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 主动断开无人船遥测SSE连接
|
* 主动断开无人船遥测SSE连接
|
||||||
*
|
|
||||||
* @param deviceSn 设备SN
|
|
||||||
* @param clientSessionId 客户端会话ID
|
|
||||||
* @return 断开结果
|
|
||||||
*/
|
*/
|
||||||
@Operation(summary = "主动断开无人船遥测SSE连接")
|
@Operation(summary = "主动断开无人船遥测SSE连接")
|
||||||
@DeleteMapping("/telemetry/{deviceSn}")
|
@DeleteMapping("/telemetry/{deviceSn}")
|
||||||
@@ -144,27 +88,18 @@ public class BoatTelemetrySseController {
|
|||||||
@Parameter(description = "客户端会话ID", required = true)
|
@Parameter(description = "客户端会话ID", required = true)
|
||||||
@RequestHeader(value = "X-Client-Session-Id") String clientSessionId) {
|
@RequestHeader(value = "X-Client-Session-Id") String clientSessionId) {
|
||||||
|
|
||||||
String connectionId = "boat_" + clientSessionId + "_" + deviceSn;
|
String sessionId = "boat_" + clientSessionId + "_" + deviceSn;
|
||||||
log.info("客户端主动断开无人船遥测SSE连接: connectionId={}, deviceSn={}", connectionId, deviceSn);
|
log.info("[无人船SSE] 客户端主动断开: session={}, deviceSn={}", sessionId, deviceSn);
|
||||||
|
|
||||||
boolean success = removeConnection(connectionId, deviceSn);
|
boolean success = boatSseEmitterManager.removeEmitterBySessionId(sessionId, deviceSn);
|
||||||
|
return ResponseEntity.ok(success ? "连接已断开" : "连接不存在或已断开");
|
||||||
if (success) {
|
|
||||||
return ResponseEntity.ok("连接已断开");
|
|
||||||
} else {
|
|
||||||
return ResponseEntity.ok("连接不存在或已断开");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Beacon方式断开无人船遥测SSE连接
|
* Beacon方式断开无人船遥测SSE连接
|
||||||
* 用于浏览器刷新/关闭时
|
* 用于浏览器刷新/关闭时,sendBeacon只支持POST请求
|
||||||
*
|
|
||||||
* @param deviceSn 设备SN
|
|
||||||
* @param body 包含sessionId的请求体
|
|
||||||
* @return 断开结果
|
|
||||||
*/
|
*/
|
||||||
@Operation(summary = "Beacon方式断开无人船遥测SSE连接")
|
@Operation(summary = "Beacon方式断开无人船遥测SSE连接(浏览器刷新/关闭时使用)")
|
||||||
@PostMapping("/telemetry/{deviceSn}/disconnect")
|
@PostMapping("/telemetry/{deviceSn}/disconnect")
|
||||||
public ResponseEntity<String> disconnectBoatTelemetryByBeacon(
|
public ResponseEntity<String> disconnectBoatTelemetryByBeacon(
|
||||||
@Parameter(description = "设备SN", required = true)
|
@Parameter(description = "设备SN", required = true)
|
||||||
@@ -173,61 +108,14 @@ public class BoatTelemetrySseController {
|
|||||||
|
|
||||||
String clientSessionId = body != null ? body.get("sessionId") : null;
|
String clientSessionId = body != null ? body.get("sessionId") : null;
|
||||||
if (clientSessionId == null || clientSessionId.trim().isEmpty()) {
|
if (clientSessionId == null || clientSessionId.trim().isEmpty()) {
|
||||||
log.warn("Beacon断开无人船SSE请求缺少sessionId: deviceSn={}", deviceSn);
|
log.warn("[无人船SSE] Beacon断开请求缺少sessionId: deviceSn={}", deviceSn);
|
||||||
return ResponseEntity.badRequest().body("缺少sessionId");
|
return ResponseEntity.badRequest().body("缺少sessionId");
|
||||||
}
|
}
|
||||||
|
|
||||||
String connectionId = "boat_" + clientSessionId + "_" + deviceSn;
|
String sessionId = "boat_" + clientSessionId + "_" + deviceSn;
|
||||||
log.info("Beacon方式断开无人船遥测SSE连接: connectionId={}, deviceSn={}", connectionId, deviceSn);
|
log.info("[无人船SSE] Beacon方式断开: session={}, deviceSn={}", sessionId, deviceSn);
|
||||||
|
|
||||||
boolean success = removeConnection(connectionId, deviceSn);
|
boolean success = boatSseEmitterManager.removeEmitterBySessionId(sessionId, deviceSn);
|
||||||
|
return ResponseEntity.ok(success ? "连接已断开" : "连接不存在或已断开");
|
||||||
if (success) {
|
|
||||||
return ResponseEntity.ok("连接已断开");
|
|
||||||
} else {
|
|
||||||
return ResponseEntity.ok("连接不存在或已断开");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ========== 私有方法 ==========
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 发送遥测数据到指定连接
|
|
||||||
*/
|
|
||||||
private void sendTelemetryData(String connectionId, BoatRealtimeVO data) {
|
|
||||||
SseEmitter emitter = emitters.get(connectionId);
|
|
||||||
if (emitter == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
emitter.send(SseEmitter.event()
|
|
||||||
.name("boat-telemetry")
|
|
||||||
.data(JSON.toJSONString(data)));
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.warn("发送遥测数据失败: connectionId={}, error={}", connectionId, e.getMessage());
|
|
||||||
// 发送失败时移除连接
|
|
||||||
String deviceSn = data.getDeviceSn();
|
|
||||||
removeConnection(connectionId, deviceSn);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 移除连接并清理资源
|
|
||||||
*/
|
|
||||||
private boolean removeConnection(String connectionId, String deviceSn) {
|
|
||||||
SseEmitter emitter = emitters.remove(connectionId);
|
|
||||||
if (emitter != null) {
|
|
||||||
try {
|
|
||||||
emitter.complete();
|
|
||||||
} catch (Exception e) {
|
|
||||||
// 忽略
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 注销遥测回调
|
|
||||||
boatTrackService.unregisterTelemetryCallback(deviceSn, connectionId);
|
|
||||||
|
|
||||||
return emitter != null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+95
-10
@@ -381,9 +381,9 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 从topic中提取deviceSn
|
* 从topic中提取deviceSn
|
||||||
* 支持的topic格式:
|
* 支持的topic格式(通用,支持任意产品类型):
|
||||||
* 1. /device/D-Dock2/{deviceSn}/... (订阅消息)
|
* 1. /device/{productType}/{deviceSn}/... (订阅消息,如 AutoDock3、ship)
|
||||||
* 2. /device-message-sender/D-Dock2/{deviceSn} (命令响应)
|
* 2. /device-message-sender/{productType}/{deviceSn} (命令响应)
|
||||||
*/
|
*/
|
||||||
private String extractDeviceSn(String topic) {
|
private String extractDeviceSn(String topic) {
|
||||||
if (topic == null) {
|
if (topic == null) {
|
||||||
@@ -393,13 +393,9 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
|
|||||||
|
|
||||||
String[] parts = topic.split("/");
|
String[] parts = topic.split("/");
|
||||||
|
|
||||||
// 格式1: /device/D-Dock2/{deviceSn}/...
|
// 通用格式: /device/{productType}/{deviceSn}/... 或 /device-message-sender/{productType}/{deviceSn}
|
||||||
if (topic.startsWith("/device/AutoDock3/") && parts.length >= 4) {
|
// parts[0] 为空字符串(topic以/开头),parts[1] 为 "device" 或 "device-message-sender",parts[3] 为 deviceSn
|
||||||
return parts[3];
|
if (parts.length >= 4 && ("device".equals(parts[1]) || "device-message-sender".equals(parts[1]))) {
|
||||||
}
|
|
||||||
|
|
||||||
// 格式2: /device-message-sender/D-Dock2/{deviceSn}
|
|
||||||
if (topic.startsWith("/device-message-sender/AutoDock3/") && parts.length >= 4) {
|
|
||||||
return parts[3];
|
return parts[3];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -543,6 +539,95 @@ public class JetLinksWebSocketClient extends TextWebSocketHandler {
|
|||||||
topic, subscriptionId, deviceSn, deviceSubscriptionCounts.get(deviceSn).get());
|
topic, subscriptionId, deviceSn, deviceSubscriptionCounts.get(deviceSn).get());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订阅指定 topic 字符串(公开方法,供非 SubscriptionTopic 枚举的产品使用)
|
||||||
|
* 将 topic 纳入 subscribedTopics 跟踪,确保消息路由不被过滤
|
||||||
|
*
|
||||||
|
* @param topic 完整 topic 路径(如 /device/ship/{deviceSn}/online)
|
||||||
|
* @param deviceSn 设备SN
|
||||||
|
*/
|
||||||
|
public void subscribeRawTopic(String topic, String deviceSn) {
|
||||||
|
if (topic == null || deviceSn == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (subscribedTopics.contains(topic)) {
|
||||||
|
log.debug("主题已订阅,跳过重复订阅: topic={}, deviceSn={}", topic, deviceSn);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String subscriptionId = "sub-" + deviceSn + "-" + UUID.randomUUID().toString().substring(0, 8);
|
||||||
|
topicSubscriptionIds.put(topic, subscriptionId);
|
||||||
|
|
||||||
|
SubscriptionMessage message = SubscriptionMessage.builder()
|
||||||
|
.type("sub")
|
||||||
|
.topic(topic)
|
||||||
|
.parameter(new JSONObject())
|
||||||
|
.id(subscriptionId)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
send(JSON.toJSONString(message));
|
||||||
|
subscribedTopics.add(topic);
|
||||||
|
|
||||||
|
deviceSubscriptionCounts.computeIfAbsent(deviceSn, k -> new AtomicInteger(0)).incrementAndGet();
|
||||||
|
|
||||||
|
log.info("发送订阅消息: topic={}, id={}, 设备{}订阅计数: {}",
|
||||||
|
topic, subscriptionId, deviceSn, deviceSubscriptionCounts.get(deviceSn).get());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消订阅指定 topic 字符串(公开方法)
|
||||||
|
*
|
||||||
|
* @param topic 完整 topic 路径
|
||||||
|
* @param deviceSn 设备SN
|
||||||
|
*/
|
||||||
|
public void unsubscribeRawTopic(String topic, String deviceSn) {
|
||||||
|
if (topic == null || deviceSn == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!subscribedTopics.contains(topic)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String subscriptionId = topicSubscriptionIds.remove(topic);
|
||||||
|
if (subscriptionId == null) {
|
||||||
|
subscriptionId = "unsub-" + UUID.randomUUID().toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
SubscriptionMessage message = SubscriptionMessage.builder()
|
||||||
|
.type("unsub")
|
||||||
|
.topic(topic)
|
||||||
|
.parameter(new JSONObject())
|
||||||
|
.id(subscriptionId)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
send(JSON.toJSONString(message));
|
||||||
|
subscribedTopics.remove(topic);
|
||||||
|
|
||||||
|
boolean hasOtherTopics = subscribedTopics.stream()
|
||||||
|
.anyMatch(t -> t.contains("/" + deviceSn + "/"));
|
||||||
|
|
||||||
|
if (!hasOtherTopics) {
|
||||||
|
deviceSubscriptionCounts.remove(deviceSn);
|
||||||
|
} else {
|
||||||
|
AtomicInteger count = deviceSubscriptionCounts.get(deviceSn);
|
||||||
|
if (count != null) {
|
||||||
|
count.decrementAndGet();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("取消订阅主题: topic={}, id={}, 剩余主题数: {}",
|
||||||
|
topic, subscriptionId, subscribedTopics.size());
|
||||||
|
|
||||||
|
// 所有主题都取消后,自动断开连接
|
||||||
|
if (subscribedTopics.isEmpty()) {
|
||||||
|
log.info("所有主题订阅已取消,自动断开WebSocket连接以节省资源");
|
||||||
|
deviceSubscriptionCounts.clear();
|
||||||
|
closeConnection();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 取消订阅主题
|
* 取消订阅主题
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -0,0 +1,691 @@
|
|||||||
|
# 无人船指令下发实现方案
|
||||||
|
|
||||||
|
## 一、背景
|
||||||
|
|
||||||
|
无人船的航线规划和任务管理已实现(技术方案见 `无人船航线规划技术方案.md`),但由于实现期间没有无人船的指令协议,`BoatControlServiceImpl` 当前为 **Mock 实现**,所有方法只修改内存状态,不发送任何 IoT 指令。
|
||||||
|
|
||||||
|
现在需要对接真实的无人船设备,参考无人机的指令下发机制,实现以下功能:
|
||||||
|
1. 订阅无人船设备消息(产品标识:`ship`)
|
||||||
|
2. 通过 WebSocket 向 JetLinks IoT 平台下发控制指令
|
||||||
|
|
||||||
|
## 二、指令协议(由设备端提供)
|
||||||
|
|
||||||
|
### 2.1 开始任务(flighttask_prepare)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"messageType": "WRITE_PROPERTY",
|
||||||
|
"deviceId": "12345678",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"order_no": "562026040600002",
|
||||||
|
"wayline_link_url": "https://minicdn.goflytec.com/goflymedia/yumenguan_guanjingtai_0918.kmz",
|
||||||
|
"file_md5": "82d1b6eaba8f2be36e5e69e07c768a8e",
|
||||||
|
"stream_urls": {
|
||||||
|
"pushUrl": "rtmp://208280.push.tlivecloud.com/live/xxx",
|
||||||
|
"playFlvUrl": "http://goflytec.com/live/xxx.flv",
|
||||||
|
"playM3u8Url": "http://goflytec.com/live/xxx.m3u8",
|
||||||
|
"playRtmpUrl": "rtmp://goflytec.com/live/xxx"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"method": "flighttask_prepare"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 暂停任务(flighttask_pause)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"messageType": "WRITE_PROPERTY",
|
||||||
|
"deviceId": "12345678",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"order_no": "562026040600002"
|
||||||
|
},
|
||||||
|
"method": "flighttask_pause"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 继续任务(flighttask_recovery)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"messageType": "WRITE_PROPERTY",
|
||||||
|
"deviceId": "12345678",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"order_no": "562026040600002"
|
||||||
|
},
|
||||||
|
"method": "flighttask_recovery"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.4 终止任务(flighttask_undo)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"messageType": "WRITE_PROPERTY",
|
||||||
|
"deviceId": "12345678",
|
||||||
|
"properties": {
|
||||||
|
"data": {
|
||||||
|
"order_no": "562026040600002"
|
||||||
|
},
|
||||||
|
"method": "flighttask_undo"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 三、架构设计原则
|
||||||
|
|
||||||
|
### 3.1 核心原则:不修改无人机代码,独立 boat 包
|
||||||
|
|
||||||
|
```
|
||||||
|
原则:
|
||||||
|
1. 不修改无人机专有代码(DeviceCommandManager、SubscriptionTopic、DeviceSubscriptionManager)
|
||||||
|
2. 新建 com.central.device.boat 包,实现无人船专有逻辑
|
||||||
|
3. 复用共享基础设施(JetLinksWebSocketClient、DeviceCommand、CommandStatus、WebSocketProperties)
|
||||||
|
4. 对共享基础设施仅做最小化通用改动(extractDeviceSn 路径解析通用化)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 无人机指令下发链路(已实现,不修改)
|
||||||
|
|
||||||
|
```
|
||||||
|
前端 HTTP 请求
|
||||||
|
→ DeviceCommandController(/device/command/pause 等)
|
||||||
|
→ DeviceCommandManager.sendCommand(deviceSn, commandType, params)
|
||||||
|
→ sendCommandImmediately()
|
||||||
|
→ buildCommandProperties() 构建 properties JSON
|
||||||
|
→ 组装 WebSocket 消息:
|
||||||
|
{
|
||||||
|
"type": "sub",
|
||||||
|
"topic": "/device-message-sender/AutoDock3/{deviceSn}",
|
||||||
|
"parameter": {
|
||||||
|
"messageType": "WRITE_PROPERTY",
|
||||||
|
"properties": { "method": "xxx", "data": {...} },
|
||||||
|
"headers": { "async": false }
|
||||||
|
},
|
||||||
|
"id": "{commandId}"
|
||||||
|
}
|
||||||
|
→ JetLinksWebSocketClient.send(json)
|
||||||
|
→ IoT 平台 → 设备
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 无人船指令下发链路(新建,独立于无人机)
|
||||||
|
|
||||||
|
```
|
||||||
|
前端 HTTP 请求
|
||||||
|
→ BoatCommandController(/device/boat/command/pause 等)
|
||||||
|
→ BoatControlServiceImpl
|
||||||
|
→ BoatCommandManager.sendCommand(deviceSn, commandType, params) ← 新建,boat 包
|
||||||
|
→ sendCommandImmediately()
|
||||||
|
→ buildCommandProperties() 构建无人船 properties JSON ← 无人船专用构建逻辑
|
||||||
|
→ 组装 WebSocket 消息:
|
||||||
|
{
|
||||||
|
"type": "sub",
|
||||||
|
"topic": "/device-message-sender/ship/{deviceSn}", ← 使用 ship 产品标识
|
||||||
|
"parameter": {
|
||||||
|
"messageType": "WRITE_PROPERTY",
|
||||||
|
"properties": { "method": "xxx", "data": { "order_no": "xxx", ... } },
|
||||||
|
"headers": { "async": false }
|
||||||
|
},
|
||||||
|
"id": "{commandId}"
|
||||||
|
}
|
||||||
|
→ JetLinksWebSocketClient.send(json) ← 复用共享 WebSocket 连接
|
||||||
|
→ IoT 平台 → 设备
|
||||||
|
```
|
||||||
|
|
||||||
|
## 四、复用与新建分析
|
||||||
|
|
||||||
|
### 4.1 复用组件(不修改)
|
||||||
|
|
||||||
|
| 组件 | 所在包 | 复用方式 | 说明 |
|
||||||
|
|------|--------|----------|------|
|
||||||
|
| `JetLinksWebSocketClient.send()` | websocket/client | 直接注入调用 | 共享全局 WebSocket 连接发送消息 |
|
||||||
|
| `DeviceCommand` | websocket/model | 直接使用 | 命令实体,包含 commandId、deviceSn、params 等 |
|
||||||
|
| `CommandStatus` | websocket/model | 直接使用 | 命令状态枚举 |
|
||||||
|
| `WebSocketProperties` | websocket/config | 注入使用 | 超时、重试等配置 |
|
||||||
|
| `DeviceMessageHandler` | websocket/handler | 共享消息处理 | topic 关键字路由(/online、/offline 等),不区分产品类型 |
|
||||||
|
| `TokenManager` | websocket/manager | 间接复用 | 通过 WebSocket 连接自动管理 Token |
|
||||||
|
|
||||||
|
### 4.2 新建组件(boat 包)
|
||||||
|
|
||||||
|
| 组件 | 路径 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| `BoatSubscriptionTopic` | boat/model | 无人船订阅主题枚举(ship 产品) |
|
||||||
|
| `BoatCommandManager` | boat/manager | 无人船命令管理器(命令构建、队列、发送) |
|
||||||
|
| `BoatSubscriptionManager` | boat/manager | 无人船设备订阅管理器 |
|
||||||
|
|
||||||
|
### 4.3 共享基础设施最小改动
|
||||||
|
|
||||||
|
| 文件 | 改动内容 | 影响 |
|
||||||
|
|------|----------|------|
|
||||||
|
| `JetLinksWebSocketClient.java` | `extractDeviceSn()` 通用化路径解析 | 向后兼容,AutoDock3 行为不变 |
|
||||||
|
|
||||||
|
### 4.4 现有无人船文件修改
|
||||||
|
|
||||||
|
| 文件 | 改动内容 |
|
||||||
|
|------|----------|
|
||||||
|
| `ControlEnum.java` | 新增 `FLIGHTTASK_UNDO` 枚举值 |
|
||||||
|
| `IBoatControlService.java` | `pause`/`resume` 增加 missionCode 参数;新增 `undoTask` 方法 |
|
||||||
|
| `BoatControlServiceImpl.java` | **重写**:Mock 实现替换为通过 `BoatCommandManager` 发送真实 IoT 指令 |
|
||||||
|
| `BoatCommandController.java` | pause/resume 接口增加 missionCode 参数;新增 undo 接口 |
|
||||||
|
|
||||||
|
## 五、详细实现方案
|
||||||
|
|
||||||
|
### 5.1 BoatSubscriptionTopic(新建)
|
||||||
|
|
||||||
|
**文件**:`boat/model/BoatSubscriptionTopic.java`
|
||||||
|
|
||||||
|
独立枚举,定义无人船的 WebSocket 订阅主题,参考 `SubscriptionTopic` 的结构。
|
||||||
|
|
||||||
|
```java
|
||||||
|
package com.central.device.boat.model;
|
||||||
|
|
||||||
|
public enum BoatSubscriptionTopic {
|
||||||
|
|
||||||
|
BOAT_ONLINE("/device/ship/{deviceSn}/online"),
|
||||||
|
BOAT_OFFLINE("/device/ship/{deviceSn}/offline"),
|
||||||
|
BOAT_EVENT_FIRE_ALARM("/device/ship/{deviceSn}/message/event/fire_alarm"),
|
||||||
|
BOAT_EVENT_MSG_ALARM("/device/ship/{deviceSn}/message/event/msg_alarm"),
|
||||||
|
BOAT_PROPERTY_REPORT("/device/ship/{deviceSn}/message/property/report");
|
||||||
|
|
||||||
|
private final String topicPattern;
|
||||||
|
|
||||||
|
BoatSubscriptionTopic(String topicPattern) {
|
||||||
|
this.topicPattern = topicPattern;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTopic(String deviceSn) {
|
||||||
|
return topicPattern.replace("{deviceSn}", deviceSn);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTopicPattern() {
|
||||||
|
return topicPattern;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.2 BoatCommandManager(新建,核心)
|
||||||
|
|
||||||
|
**文件**:`boat/manager/BoatCommandManager.java`
|
||||||
|
|
||||||
|
参考 `DeviceCommandManager` 的核心逻辑,精简为无人船场景。
|
||||||
|
|
||||||
|
**与 DeviceCommandManager 的关键区别**:
|
||||||
|
1. **topic 使用 `ship`**:`/device-message-sender/ship/{deviceSn}`
|
||||||
|
2. **buildCommandProperties()** 只处理无人船 4 种指令
|
||||||
|
3. **无人船指令 data 中需要 `order_no`**(无人机的 pause/recovery 不需要)
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class BoatCommandManager {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private WebSocketProperties properties;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private JetLinksWebSocketClient jetLinksWebSocketClient;
|
||||||
|
|
||||||
|
public static final String PRODUCT_BOAT = "ship";
|
||||||
|
|
||||||
|
// 命令队列和待响应列表(与 DeviceCommandManager 结构相同)
|
||||||
|
private final ConcurrentHashMap<String, ConcurrentLinkedQueue<DeviceCommand>> commandQueues = new ConcurrentHashMap<>();
|
||||||
|
private final ConcurrentHashMap<String, DeviceCommand> pendingCommands = new ConcurrentHashMap<>();
|
||||||
|
private final ScheduledExecutorService retryExecutor = Executors.newScheduledThreadPool(2);
|
||||||
|
|
||||||
|
public String sendCommand(String deviceSn, String commandType, JSONObject params) {
|
||||||
|
// 1. 创建 DeviceCommand(复用现有模型)
|
||||||
|
// 2. 检查 WebSocket 连接
|
||||||
|
// 3. 连接成功则 sendCommandImmediately,否则加入队列
|
||||||
|
// (逻辑与 DeviceCommandManager.sendCommand 相同)
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendCommandImmediately(DeviceCommand command) {
|
||||||
|
// 构造指令 properties
|
||||||
|
JSONObject props = buildCommandProperties(command);
|
||||||
|
|
||||||
|
// 组装完整消息
|
||||||
|
JSONObject message = new JSONObject();
|
||||||
|
message.put("type", "sub");
|
||||||
|
message.put("topic", "/device-message-sender/" + PRODUCT_BOAT + "/" + command.getDeviceSn());
|
||||||
|
// ... parameter、headers、id
|
||||||
|
// 通过共享 WebSocket 发送
|
||||||
|
jetLinksWebSocketClient.send(message.toJSONString());
|
||||||
|
}
|
||||||
|
|
||||||
|
private JSONObject buildCommandProperties(DeviceCommand command) {
|
||||||
|
JSONObject properties = new JSONObject();
|
||||||
|
JSONObject data = new JSONObject();
|
||||||
|
String method = command.getCommandType();
|
||||||
|
JSONObject params = command.getParams();
|
||||||
|
|
||||||
|
switch (method) {
|
||||||
|
case "flighttask_prepare":
|
||||||
|
data.put("order_no", params.getString("order_no"));
|
||||||
|
data.put("wayline_link_url", params.getString("wayline_link_url"));
|
||||||
|
data.put("file_md5", params.getString("file_md5"));
|
||||||
|
if (params.containsKey("stream_urls")) {
|
||||||
|
data.put("stream_urls", params.get("stream_urls"));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "flighttask_pause":
|
||||||
|
case "flighttask_recovery":
|
||||||
|
case "flighttask_undo":
|
||||||
|
data.put("order_no", params.getString("order_no"));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
data = params;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
properties.put("method", method);
|
||||||
|
properties.put("data", data);
|
||||||
|
return properties;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 队列管理、重试、超时清理等方法(与 DeviceCommandManager 结构相同)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> **设计说明**:commandType 直接使用 IoT 平台的 method 名称(`flighttask_prepare` 等),不再使用 `boat_` 前缀。因为 `BoatCommandManager` 本身就是无人船专用,无需前缀区分。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.3 BoatSubscriptionManager(新建)
|
||||||
|
|
||||||
|
**文件**:`boat/manager/BoatSubscriptionManager.java`
|
||||||
|
|
||||||
|
无人船设备订阅管理器,参考 `DeviceSubscriptionManager` 的单设备订阅模式。
|
||||||
|
|
||||||
|
由于 `JetLinksWebSocketClient.subscribeDevice()` 接受 `SubscriptionTopic` 枚举类型,而 `BoatSubscriptionTopic` 是独立枚举,因此无人船订阅管理器直接调用 `JetLinksWebSocketClient.send()` 手动构建订阅/取消订阅消息。
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class BoatSubscriptionManager {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private JetLinksWebSocketClient jetLinksWebSocketClient;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private DeviceMessageHandler messageHandler;
|
||||||
|
|
||||||
|
public void subscribeBoatDevice(String deviceSn, String tenantId) {
|
||||||
|
messageHandler.addDevice(deviceSn, 0L, tenantId);
|
||||||
|
subscribeTopic(deviceSn, BoatSubscriptionTopic.BOAT_ONLINE);
|
||||||
|
subscribeTopic(deviceSn, BoatSubscriptionTopic.BOAT_OFFLINE);
|
||||||
|
subscribeTopic(deviceSn, BoatSubscriptionTopic.BOAT_EVENT_FIRE_ALARM);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void subscribeBoatTelemetry(String deviceSn) {
|
||||||
|
subscribeTopic(deviceSn, BoatSubscriptionTopic.BOAT_EVENT_MSG_ALARM);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void unsubscribeBoatDevice(String deviceSn) {
|
||||||
|
unsubscribeTopic(deviceSn, BoatSubscriptionTopic.BOAT_ONLINE);
|
||||||
|
unsubscribeTopic(deviceSn, BoatSubscriptionTopic.BOAT_OFFLINE);
|
||||||
|
unsubscribeTopic(deviceSn, BoatSubscriptionTopic.BOAT_EVENT_FIRE_ALARM);
|
||||||
|
unsubscribeTopic(deviceSn, BoatSubscriptionTopic.BOAT_EVENT_MSG_ALARM);
|
||||||
|
messageHandler.removeDevice(deviceSn);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void subscribeTopic(String deviceSn, BoatSubscriptionTopic topicEnum) {
|
||||||
|
String topic = topicEnum.getTopic(deviceSn);
|
||||||
|
// 手动构建订阅消息 JSON,调用 jetLinksWebSocketClient.send()
|
||||||
|
}
|
||||||
|
|
||||||
|
private void unsubscribeTopic(String deviceSn, BoatSubscriptionTopic topicEnum) {
|
||||||
|
String topic = topicEnum.getTopic(deviceSn);
|
||||||
|
// 手动构建取消订阅消息 JSON,调用 jetLinksWebSocketClient.send()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.4 JetLinksWebSocketClient.extractDeviceSn() 通用化
|
||||||
|
|
||||||
|
**文件**:`websocket/client/JetLinksWebSocketClient.java`(第 388-407 行)
|
||||||
|
|
||||||
|
**改动前**(仅支持 AutoDock3):
|
||||||
|
```java
|
||||||
|
private String extractDeviceSn(String topic) {
|
||||||
|
if (topic == null) { return null; }
|
||||||
|
String[] parts = topic.split("/");
|
||||||
|
if (topic.startsWith("/device/AutoDock3/") && parts.length >= 4) { return parts[3]; }
|
||||||
|
if (topic.startsWith("/device-message-sender/AutoDock3/") && parts.length >= 4) { return parts[3]; }
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**改动后**(支持任意产品类型):
|
||||||
|
```java
|
||||||
|
private String extractDeviceSn(String topic) {
|
||||||
|
if (topic == null) { return null; }
|
||||||
|
String[] parts = topic.split("/");
|
||||||
|
// 通用格式: /device/{productType}/{deviceSn}/... 或 /device-message-sender/{productType}/{deviceSn}
|
||||||
|
if (parts.length >= 4 && ("device".equals(parts[1]) || "device-message-sender".equals(parts[1]))) {
|
||||||
|
return parts[3];
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**向后兼容性**:`/device/AutoDock3/{deviceSn}/...` 路径中 `parts[1]` 为 `"device"`,`parts[3]` 为 `deviceSn`,行为完全不变。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.5 ControlEnum 新增终止任务
|
||||||
|
|
||||||
|
**文件**:`message/ControlEnum.java`
|
||||||
|
|
||||||
|
```java
|
||||||
|
FLIGHTTASK_UNDO("flighttask_undo");
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.6 IBoatControlService 接口扩展
|
||||||
|
|
||||||
|
**文件**:`service/IBoatControlService.java`
|
||||||
|
|
||||||
|
#### 修改现有方法签名(暂停/恢复需要 missionCode)
|
||||||
|
|
||||||
|
```java
|
||||||
|
void pause(String deviceSn, String missionCode);
|
||||||
|
void resume(String deviceSn, String missionCode);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 新增方法
|
||||||
|
|
||||||
|
```java
|
||||||
|
void undoTask(String deviceSn, String missionCode);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.7 BoatControlServiceImpl 重写(核心)
|
||||||
|
|
||||||
|
**文件**:`service/impl/BoatControlServiceImpl.java`
|
||||||
|
|
||||||
|
将 Mock 实现替换为真实 IoT 指令下发。
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class BoatControlServiceImpl implements IBoatControlService {
|
||||||
|
|
||||||
|
private final IBoatRouteService boatRouteService;
|
||||||
|
private final BoatCommandManager boatCommandManager; // 使用无人船专用命令管理器
|
||||||
|
private final IAgeDeviceService ageDeviceService;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String executeRoute(String deviceSn, String boatRouteId, String missionCode) {
|
||||||
|
BoatRoute route = boatRouteService.getByRouteId(boatRouteId);
|
||||||
|
if (route == null) { throw new BusinessException("航线不存在"); }
|
||||||
|
|
||||||
|
JSONObject params = new JSONObject();
|
||||||
|
params.put("order_no", missionCode);
|
||||||
|
params.put("wayline_link_url", route.getRouteFileUrl());
|
||||||
|
params.put("file_md5", "");
|
||||||
|
params.put("stream_urls", getStreamUrls(deviceSn));
|
||||||
|
|
||||||
|
String commandId = boatCommandManager.sendCommand(deviceSn, "flighttask_prepare", params);
|
||||||
|
boatRouteService.updateStatus(boatRouteId, BoatRoute.RouteStatus.EXECUTING.getCode());
|
||||||
|
return commandId;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void pause(String deviceSn, String missionCode) {
|
||||||
|
JSONObject params = new JSONObject();
|
||||||
|
params.put("order_no", missionCode);
|
||||||
|
boatCommandManager.sendCommand(deviceSn, "flighttask_pause", params);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void resume(String deviceSn, String missionCode) {
|
||||||
|
JSONObject params = new JSONObject();
|
||||||
|
params.put("order_no", missionCode);
|
||||||
|
boatCommandManager.sendCommand(deviceSn, "flighttask_recovery", params);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void undoTask(String deviceSn, String missionCode) {
|
||||||
|
JSONObject params = new JSONObject();
|
||||||
|
params.put("order_no", missionCode);
|
||||||
|
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", params);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void returnToStart(String deviceSn) {
|
||||||
|
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", new JSONObject());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void emergencyStop(String deviceSn) {
|
||||||
|
boatCommandManager.sendCommand(deviceSn, "flighttask_undo", new JSONObject());
|
||||||
|
}
|
||||||
|
|
||||||
|
// manualControl、isDeviceOnline、getDeviceStatus 暂保留接口
|
||||||
|
// 删除所有 Mock 相关代码
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> **删除内容**:移除 `DeviceState` 内部类、`deviceStates` Map、所有 `mock*()` 方法、`getOrCreateDeviceState()` 方法。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5.8 BoatCommandController 修改
|
||||||
|
|
||||||
|
**文件**:`controller/BoatCommandController.java`
|
||||||
|
|
||||||
|
#### 修改暂停/恢复接口,增加 missionCode 参数
|
||||||
|
|
||||||
|
```java
|
||||||
|
@PostMapping("/pause")
|
||||||
|
public Result<Void> pause(@RequestParam String deviceSn, @RequestParam String missionCode) {
|
||||||
|
boatControlService.pause(deviceSn, missionCode);
|
||||||
|
return Result.succeed(null, "暂停指令已下发");
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/resume")
|
||||||
|
public Result<Void> resume(@RequestParam String deviceSn, @RequestParam String missionCode) {
|
||||||
|
boatControlService.resume(deviceSn, missionCode);
|
||||||
|
return Result.succeed(null, "恢复指令已下发");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 新增终止任务接口
|
||||||
|
|
||||||
|
```java
|
||||||
|
@PostMapping("/undo")
|
||||||
|
public Result<Void> undoTask(@RequestParam String deviceSn, @RequestParam String missionCode) {
|
||||||
|
boatControlService.undoTask(deviceSn, missionCode);
|
||||||
|
return Result.succeed(null, "终止任务指令已下发");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 六、接口变更汇总
|
||||||
|
|
||||||
|
### 新增接口
|
||||||
|
|
||||||
|
| 方法 | 路径 | 参数 | 说明 |
|
||||||
|
|------|------|------|------|
|
||||||
|
| POST | `/device/boat/command/undo` | deviceSn, missionCode | 终止任务 |
|
||||||
|
|
||||||
|
### 修改接口
|
||||||
|
|
||||||
|
| 方法 | 路径 | 变更 | 说明 |
|
||||||
|
|------|------|------|------|
|
||||||
|
| POST | `/device/boat/command/pause` | 新增 `missionCode` 参数 | 暂停任务需要传 order_no |
|
||||||
|
| POST | `/device/boat/command/resume` | 新增 `missionCode` 参数 | 恢复任务需要传 order_no |
|
||||||
|
|
||||||
|
### 不变接口
|
||||||
|
|
||||||
|
| 方法 | 路径 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| POST | `/device/boat/command/route/execute` | 执行航线(已有 missionCode 参数) |
|
||||||
|
| POST | `/device/boat/command/return` | 返回起点 |
|
||||||
|
| POST | `/device/boat/command/emergency-stop` | 紧急停止 |
|
||||||
|
| POST | `/device/boat/command/manual` | 手动控制(暂保留,待后续协议) |
|
||||||
|
| GET | `/device/boat/command/online/{deviceSn}` | 检查设备在线 |
|
||||||
|
| GET | `/device/boat/command/status/{deviceSn}` | 获取设备状态 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 七、新建文件清单
|
||||||
|
|
||||||
|
| # | 文件路径 | 类型 | 说明 |
|
||||||
|
|---|---------|------|------|
|
||||||
|
| 1 | `boat/model/BoatSubscriptionTopic.java` | **新建** | 无人船订阅主题枚举 |
|
||||||
|
| 2 | `boat/manager/BoatCommandManager.java` | **新建** | 无人船命令管理器 |
|
||||||
|
| 3 | `boat/manager/BoatSubscriptionManager.java` | **新建** | 无人船订阅管理器 |
|
||||||
|
|
||||||
|
## 八、修改文件清单
|
||||||
|
|
||||||
|
| # | 文件路径 | 修改类型 | 说明 |
|
||||||
|
|---|---------|----------|------|
|
||||||
|
| 1 | `websocket/client/JetLinksWebSocketClient.java` | 最小改动 | `extractDeviceSn()` 通用化(唯一共享改动) |
|
||||||
|
| 2 | `message/ControlEnum.java` | 追加 | 新增 `FLIGHTTASK_UNDO` 枚举值 |
|
||||||
|
| 3 | `service/IBoatControlService.java` | 修改 | 接口签名调整 + 新增方法 |
|
||||||
|
| 4 | `service/impl/BoatControlServiceImpl.java` | **重写** | Mock → 真实 IoT 指令下发 |
|
||||||
|
| 5 | `controller/BoatCommandController.java` | 修改 | 接口参数调整 + 新增 undo |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 九、WebSocket 消息格式对比
|
||||||
|
|
||||||
|
### 无人机指令(现有,不变)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "sub",
|
||||||
|
"topic": "/device-message-sender/AutoDock3/{deviceSn}",
|
||||||
|
"parameter": {
|
||||||
|
"messageType": "WRITE_PROPERTY",
|
||||||
|
"properties": {
|
||||||
|
"method": "flighttask_pause",
|
||||||
|
"data": {}
|
||||||
|
},
|
||||||
|
"headers": { "async": false }
|
||||||
|
},
|
||||||
|
"id": "{commandId}"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 无人船指令(新增)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "sub",
|
||||||
|
"topic": "/device-message-sender/ship/{deviceSn}",
|
||||||
|
"parameter": {
|
||||||
|
"messageType": "WRITE_PROPERTY",
|
||||||
|
"properties": {
|
||||||
|
"method": "flighttask_pause",
|
||||||
|
"data": { "order_no": "562026040600002" }
|
||||||
|
},
|
||||||
|
"headers": { "async": false }
|
||||||
|
},
|
||||||
|
"id": "{commandId}"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**区别**:
|
||||||
|
1. topic 路径中产品标识不同:`AutoDock3` vs `ship`
|
||||||
|
2. 无人船的暂停/恢复/终止 data 中需要携带 `order_no`
|
||||||
|
3. 无人船的开始任务 data 中需要携带 `order_no`、`wayline_link_url`、`file_md5`、`stream_urls`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 十、向后兼容性保证
|
||||||
|
|
||||||
|
1. **无人机代码完全不变**:`DeviceCommandManager`、`SubscriptionTopic`、`DeviceSubscriptionManager` 零修改
|
||||||
|
2. **extractDeviceSn() 通用化**:将硬编码 `AutoDock3` 改为通用路径解析,现有 AutoDock3 路径行为完全不变
|
||||||
|
3. **ControlEnum 追加枚举值**:不影响现有枚举
|
||||||
|
4. **独立 boat 包**:所有无人船新代码在 `com.central.device.boat` 包下,物理隔离
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 十一、SSE 实时数据推送
|
||||||
|
|
||||||
|
### 11.1 架构设计
|
||||||
|
|
||||||
|
无人船 SSE 独立于无人机 SSE,在 `boat/sse` 包下实现完整的连接管理。
|
||||||
|
|
||||||
|
```
|
||||||
|
前端 GET /sse/boat/telemetry/{deviceSn}
|
||||||
|
→ BoatTelemetrySseController
|
||||||
|
→ BoatSseEmitterManager.addEmitter()
|
||||||
|
→ BoatSubscriptionManager 订阅 WebSocket 主题(ship 产品)
|
||||||
|
→ SubscriptionPoolService 添加 Redis 订阅记录
|
||||||
|
→ DeviceMessageHandler.registerMsgAlarmCallback() 注册回调
|
||||||
|
→ 返回 SseEmitter
|
||||||
|
|
||||||
|
IoT 设备消息到达:
|
||||||
|
JetLinksWebSocketClient → DeviceMessageHandler.handleMsgAlarmEvent()
|
||||||
|
→ msgAlarmCallback(由 BoatSseEmitterManager 注册)
|
||||||
|
→ BoatSseEmitterManager.sendBoatDataUpdate()
|
||||||
|
→ SseEmitter.send() 推送到前端
|
||||||
|
```
|
||||||
|
|
||||||
|
### 11.2 新建文件
|
||||||
|
|
||||||
|
| 文件 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| `boat/sse/BoatSseEmitterManager.java` | 无人船 SSE 连接管理器 |
|
||||||
|
|
||||||
|
### 11.3 修改文件
|
||||||
|
|
||||||
|
| 文件 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| `sse/controller/BoatTelemetrySseController.java` | 重写:使用 BoatSseEmitterManager 替代 IBoatTrackService 回调 |
|
||||||
|
|
||||||
|
### 11.4 复用组件
|
||||||
|
|
||||||
|
| 组件 | 复用方式 |
|
||||||
|
|------|----------|
|
||||||
|
| `BoatSubscriptionManager` | WebSocket 主题订阅/取消 |
|
||||||
|
| `SubscriptionPoolService` | Redis 订阅池(多客户端隔离) |
|
||||||
|
| `DeviceMessageHandler` | 注册 msgAlarmCallback 接收 IoT 消息 |
|
||||||
|
| `EmitterWrapper` | SSE 连接包装器 |
|
||||||
|
|
||||||
|
### 11.5 SSE 接口
|
||||||
|
|
||||||
|
| 方法 | 路径 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| GET | `/sse/boat/telemetry/{deviceSn}` | 订阅无人船遥测数据 |
|
||||||
|
| DELETE | `/sse/boat/telemetry/{deviceSn}` | 主动断开连接 |
|
||||||
|
| POST | `/sse/boat/telemetry/{deviceSn}/disconnect` | Beacon方式断开(浏览器刷新/关闭) |
|
||||||
|
|
||||||
|
### 11.6 SSE 事件格式
|
||||||
|
|
||||||
|
```
|
||||||
|
event: connected
|
||||||
|
data: {"status":"connected","deviceSn":"12345678"}
|
||||||
|
|
||||||
|
event: boat-telemetry
|
||||||
|
data: {"eventType":"msg_alarm","timestamp":1712500000,"droneData":{...}}
|
||||||
|
id: boat-1712500000
|
||||||
|
|
||||||
|
event: heartbeat
|
||||||
|
data: ping
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 十二、待确认事项
|
||||||
|
|
||||||
|
1. **无人船航线文件的 MD5**:当前 `BoatRoute` 实体没有 MD5 字段。如果设备端需要校验,需要在航线上传时计算并存储。本方案中暂传空字符串。
|
||||||
|
2. **返航/紧急停止指令**:目前映射到 `flighttask_undo`。如果无人船有专用的返航指令,后续需要替换。
|
||||||
|
3. **手动控制协议**:`manualControl()` 方法暂保留接口,待后续提供手动控制协议后对接。
|
||||||
|
4. **设备在线状态/设备状态查询**:`isDeviceOnline()` 和 `getDeviceStatus()` 暂返回默认值,后续可对接 DeviceMessageHandler 中的实时数据。
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
# 设备实时状态上报接口字段说明(前端专用)
|
||||||
|
## 一、报文结构(完整 JSON)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"tid": "",
|
||||||
|
"deviceId": "",
|
||||||
|
"bid": "",
|
||||||
|
"timestamp": "",
|
||||||
|
"data": {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 二、外层字段(报文头)
|
||||||
|
| 字段名 | 类型 | 必填 | 说明 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| tid | String | 是 | 报文唯一事务ID,用于日志追踪 |
|
||||||
|
| deviceId | String | 是 | 设备唯一编号(通用ID) |
|
||||||
|
| bid | String | 是 | 业务ID/批次ID,用于业务分组 |
|
||||||
|
| timestamp | String | 是 | 报文时间戳(建议**毫秒级**) |
|
||||||
|
|
||||||
|
## 三、data 字段(设备实时数据)
|
||||||
|
| 字段名 | 类型 | 说明 | 备注/枚举 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| deviceId | String | 设备真实ID | 建议与外层 deviceId 一致 |
|
||||||
|
| speed | Number | 实时速度 | 单位:m/s 或节(kn) |
|
||||||
|
| heading | Number | 航向角 | 0~360°,0=正北,顺时针递增 |
|
||||||
|
| longitude | Number | 经度 | WGS84 坐标系 |
|
||||||
|
| latitude | Number | 纬度 | WGS84 坐标系 |
|
||||||
|
| altitude | Number | 高度/海拔 | 单位:米 |
|
||||||
|
| navMode | String | 航行模式 | auto:自动<br>manual:手动<br>remote:遥控<br>standby:待机 |
|
||||||
|
| battery | Number | 当前电量 | 0~100,单位:% |
|
||||||
|
| signal | String | 网络信号 | 4G / 5G / NONE |
|
||||||
|
| waypointIndex | Number | 当前航点序号 | 从1开始,无航点赋值 -1 |
|
||||||
|
| deviceStatus | String | 设备状态 | normal:正常<br>warning:告警<br>error:故障<br>offline:离线 |
|
||||||
|
|
||||||
|
## 四、默认空值模板(前端初始化可用)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"tid": "",
|
||||||
|
"deviceId": "",
|
||||||
|
"bid": "",
|
||||||
|
"timestamp": "",
|
||||||
|
"data": {
|
||||||
|
"deviceId": "",
|
||||||
|
"speed": 0,
|
||||||
|
"heading": 0,
|
||||||
|
"longitude": 0,
|
||||||
|
"latitude": 0,
|
||||||
|
"altitude": 0,
|
||||||
|
"navMode": "",
|
||||||
|
"battery": 0,
|
||||||
|
"signal": "",
|
||||||
|
"waypointIndex": -1,
|
||||||
|
"deviceStatus": ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
<mapper namespace="com.central.device.mapper.BoatRouteMapper">
|
<mapper namespace="com.central.device.mapper.BoatRouteMapper">
|
||||||
|
|
||||||
<!-- 通用查询映射结果 -->
|
<!-- 通用查询映射结果 -->
|
||||||
<resultMap id="BaseResultMap" type="com.central.device.entity.BoatRoute">
|
<resultMap id="BaseResultMap" type="com.central.device.boat.entity.BoatRoute">
|
||||||
<id column="id" property="id" />
|
<id column="id" property="id" />
|
||||||
<result column="route_id" property="routeId" />
|
<result column="route_id" property="routeId" />
|
||||||
<result column="route_name" property="routeName" />
|
<result column="route_name" property="routeName" />
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<mapper namespace="com.central.device.mapper.BoatTrackMapper">
|
<mapper namespace="com.central.device.mapper.BoatTrackMapper">
|
||||||
|
|
||||||
<!-- 通用查询映射结果 -->
|
<!-- 通用查询映射结果 -->
|
||||||
<resultMap id="BaseResultMap" type="com.central.device.entity.BoatTrack">
|
<resultMap id="BaseResultMap" type="com.central.device.boat.entity.BoatTrack">
|
||||||
<id column="id" property="id" />
|
<id column="id" property="id" />
|
||||||
<result column="device_sn" property="deviceSn" />
|
<result column="device_sn" property="deviceSn" />
|
||||||
<result column="route_id" property="routeId" />
|
<result column="route_id" property="routeId" />
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<mapper namespace="com.central.device.mapper.BoatWaypointMapper">
|
<mapper namespace="com.central.device.mapper.BoatWaypointMapper">
|
||||||
|
|
||||||
<!-- 通用查询映射结果 -->
|
<!-- 通用查询映射结果 -->
|
||||||
<resultMap id="BaseResultMap" type="com.central.device.entity.BoatWaypoint">
|
<resultMap id="BaseResultMap" type="com.central.device.boat.entity.BoatWaypoint">
|
||||||
<id column="id" property="id" />
|
<id column="id" property="id" />
|
||||||
<result column="waypoint_id" property="waypointId" />
|
<result column="waypoint_id" property="waypointId" />
|
||||||
<result column="route_id" property="routeId" />
|
<result column="route_id" property="routeId" />
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<mapper namespace="com.central.device.mapper.DroneFlightTrackMapper">
|
<mapper namespace="com.central.device.mapper.DroneFlightTrackMapper">
|
||||||
|
|
||||||
<!-- 通用查询映射结果 -->
|
<!-- 通用查询映射结果 -->
|
||||||
<resultMap id="BaseResultMap" type="com.central.device.entity.DroneFlightTrack">
|
<resultMap id="BaseResultMap" type="com.central.device.boat.entity.DroneFlightTrack">
|
||||||
<id column="id" property="id" />
|
<id column="id" property="id" />
|
||||||
<result column="device_sn" property="deviceSn" />
|
<result column="device_sn" property="deviceSn" />
|
||||||
<result column="job_id" property="jobId" />
|
<result column="job_id" property="jobId" />
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<mapper namespace="com.central.device.mapper.WaterBoundaryMapper">
|
<mapper namespace="com.central.device.mapper.WaterBoundaryMapper">
|
||||||
|
|
||||||
<!-- 通用查询映射结果 -->
|
<!-- 通用查询映射结果 -->
|
||||||
<resultMap id="BaseResultMap" type="com.central.device.entity.WaterBoundary">
|
<resultMap id="BaseResultMap" type="com.central.device.boat.entity.WaterBoundary">
|
||||||
<id column="id" property="id" />
|
<id column="id" property="id" />
|
||||||
<result column="boundary_id" property="boundaryId" />
|
<result column="boundary_id" property="boundaryId" />
|
||||||
<result column="boundary_name" property="boundaryName" />
|
<result column="boundary_name" property="boundaryName" />
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<mapper namespace="com.central.device.mapper.WaylineActionMapper">
|
<mapper namespace="com.central.device.mapper.WaylineActionMapper">
|
||||||
|
|
||||||
<!-- 通用查询映射结果 -->
|
<!-- 通用查询映射结果 -->
|
||||||
<resultMap id="BaseResultMap" type="com.central.device.entity.WaylineAction">
|
<resultMap id="BaseResultMap" type="com.central.device.boat.entity.WaylineAction">
|
||||||
<id column="id" property="id" />
|
<id column="id" property="id" />
|
||||||
<result column="waypoint_id" property="waypointId" />
|
<result column="waypoint_id" property="waypointId" />
|
||||||
<result column="route_id" property="routeId" />
|
<result column="route_id" property="routeId" />
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<mapper namespace="com.central.device.mapper.WaylineRouteMapper">
|
<mapper namespace="com.central.device.mapper.WaylineRouteMapper">
|
||||||
|
|
||||||
<!-- 通用查询映射结果 -->
|
<!-- 通用查询映射结果 -->
|
||||||
<resultMap id="BaseResultMap" type="com.central.device.entity.WaylineRoute">
|
<resultMap id="BaseResultMap" type="com.central.device.boat.entity.WaylineRoute">
|
||||||
<id column="id" property="id" />
|
<id column="id" property="id" />
|
||||||
<result column="route_id" property="routeId" />
|
<result column="route_id" property="routeId" />
|
||||||
<result column="route_name" property="routeName" />
|
<result column="route_name" property="routeName" />
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<mapper namespace="com.central.device.mapper.WaylineWaypointMapper">
|
<mapper namespace="com.central.device.mapper.WaylineWaypointMapper">
|
||||||
|
|
||||||
<!-- 通用查询映射结果 -->
|
<!-- 通用查询映射结果 -->
|
||||||
<resultMap id="BaseResultMap" type="com.central.device.entity.WaylineWaypoint">
|
<resultMap id="BaseResultMap" type="com.central.device.boat.entity.WaylineWaypoint">
|
||||||
<id column="id" property="id" />
|
<id column="id" property="id" />
|
||||||
<result column="route_id" property="routeId" />
|
<result column="route_id" property="routeId" />
|
||||||
<result column="waypoint_index" property="waypointIndex" />
|
<result column="waypoint_index" property="waypointIndex" />
|
||||||
|
|||||||
+64
@@ -1,10 +1,13 @@
|
|||||||
package com.central.order.controller;
|
package com.central.order.controller;
|
||||||
|
|
||||||
import com.central.common.context.TenantContextHolder;
|
import com.central.common.context.TenantContextHolder;
|
||||||
|
import com.central.common.feign.UserService;
|
||||||
|
import com.central.common.model.SysUser;
|
||||||
import com.central.order.enums.OrderStatus;
|
import com.central.order.enums.OrderStatus;
|
||||||
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;
|
||||||
|
import com.central.order.service.ICtripDistOrderService;
|
||||||
import com.central.order.service.IOrderService;
|
import com.central.order.service.IOrderService;
|
||||||
import com.central.order.service.IQrCodeService;
|
import com.central.order.service.IQrCodeService;
|
||||||
import com.central.order.service.IRefundService;
|
import com.central.order.service.IRefundService;
|
||||||
@@ -17,13 +20,16 @@ import com.wechat.pay.java.service.payments.model.Transaction;
|
|||||||
import com.wechat.pay.java.service.refund.model.RefundNotification;
|
import com.wechat.pay.java.service.refund.model.RefundNotification;
|
||||||
import com.wechat.pay.java.service.refund.model.Status;
|
import com.wechat.pay.java.service.refund.model.Status;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jodd.util.StringUtil;
|
||||||
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.beans.factory.annotation.Value;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@RestController
|
@RestController
|
||||||
@@ -47,6 +53,12 @@ public class WxPayController {
|
|||||||
@Value("${zlt.tenant.id}")
|
@Value("${zlt.tenant.id}")
|
||||||
private String defaultTenantId;
|
private String defaultTenantId;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ICtripDistOrderService ctripDistOrderService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private UserService userService;
|
||||||
|
|
||||||
@PostMapping("/pay/notify")
|
@PostMapping("/pay/notify")
|
||||||
public String handleCallback(@RequestHeader("Wechatpay-Signature") String signature,
|
public String handleCallback(@RequestHeader("Wechatpay-Signature") String signature,
|
||||||
@RequestHeader("Wechatpay-Timestamp") String timestamp,
|
@RequestHeader("Wechatpay-Timestamp") String timestamp,
|
||||||
@@ -149,6 +161,32 @@ public class WxPayController {
|
|||||||
order.setPayTime(new Date());
|
order.setPayTime(new Date());
|
||||||
orderService.updateOrder(order);
|
orderService.updateOrder(order);
|
||||||
|
|
||||||
|
// === 携程分销订单创建 ===
|
||||||
|
if (Integer.valueOf(1).equals(qrCode.getEnableCtripOrder())) {
|
||||||
|
log.info("二维码已开启携程分销,异步创建携程订单,orderNo: {}, ctripProductId: {}",
|
||||||
|
order.getOrderNo(), qrCode.getCtripProductId());
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
@@ -185,6 +223,32 @@ public class WxPayController {
|
|||||||
order.setPayTime(new Date());
|
order.setPayTime(new Date());
|
||||||
orderService.updateOrder(order);
|
orderService.updateOrder(order);
|
||||||
|
|
||||||
|
// === 携程分销订单创建 ===
|
||||||
|
if (Integer.valueOf(1).equals(qrCode.getEnableCtripOrder())) {
|
||||||
|
log.info("二维码已开启携程分销,异步创建携程订单,orderNo: {}, ctripProductId: {}",
|
||||||
|
order.getOrderNo(), qrCode.getCtripProductId());
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
|
|||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
package com.central.order.feign;
|
||||||
|
|
||||||
|
import com.central.common.constant.ServiceNameConstants;
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import com.central.order.feign.fallback.CouponCenterServiceFallbackFactory;
|
||||||
|
import org.springframework.cloud.openfeign.FeignClient;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@FeignClient(name = ServiceNameConstants.COUPON_SERVICE, fallbackFactory = CouponCenterServiceFallbackFactory.class, dismiss404 = true)
|
||||||
|
public interface CouponCenterService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建携程分销订单
|
||||||
|
*/
|
||||||
|
@PostMapping("/ctrip/dist/order/create")
|
||||||
|
Result<String> createCtripDistOrder(@RequestBody Map<String, Object> params);
|
||||||
|
}
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
package com.central.order.feign.fallback;
|
||||||
|
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import com.central.order.feign.CouponCenterService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.cloud.openfeign.FallbackFactory;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class CouponCenterServiceFallbackFactory implements FallbackFactory<CouponCenterService> {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CouponCenterService create(Throwable cause) {
|
||||||
|
return new CouponCenterService() {
|
||||||
|
@Override
|
||||||
|
public Result<String> createCtripDistOrder(Map<String, Object> params) {
|
||||||
|
log.error("调用coupon-center创建携程分销订单失败,params: {}", params, cause);
|
||||||
|
return Result.failed("调用coupon-center失败: " + cause.getMessage());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-5
@@ -94,16 +94,17 @@ public class MissionController {
|
|||||||
return createResult;
|
return createResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 一键起飞任务:创建后自动执行
|
// 一键起飞任务 / 无人船航线任务:创建后自动执行
|
||||||
if (MissionType.isTakeoffTask(missionType)) {
|
if (MissionType.isTakeoffTask(missionType) || MissionType.isBoatRouteTask(missionType)) {
|
||||||
boolean dispatched = missionService.dispatchMissionToDevice(mission);
|
boolean dispatched = missionService.dispatchMissionToDevice(mission);
|
||||||
if (!dispatched) {
|
if (!dispatched) {
|
||||||
log.warn("一键起飞任务创建成功但下发失败: {}", mission.getMissionCode());
|
log.warn("任务创建成功但下发失败: {}", mission.getMissionCode());
|
||||||
return Result.failed("任务创建成功但执行失败,请重试");
|
return Result.failed("任务创建成功但执行失败,请重试");
|
||||||
}
|
}
|
||||||
return Result.succeed(mission, "一键起飞任务已执行");
|
String msg = MissionType.isTakeoffTask(missionType) ? "一键起飞任务已执行" : "无人船航线任务已执行";
|
||||||
|
return Result.succeed(mission, msg);
|
||||||
}
|
}
|
||||||
// 航线任务:只创建,不自动执行
|
// 无人机航线任务:只创建,不自动执行
|
||||||
return Result.succeed(mission, "任务创建成功,请确认执行");
|
return Result.succeed(mission, "任务创建成功,请确认执行");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("创建任务异常", e);
|
log.error("创建任务异常", e);
|
||||||
|
|||||||
@@ -120,4 +120,16 @@ public class QrCode extends SuperEntity {
|
|||||||
@Schema(description = "描述")
|
@Schema(description = "描述")
|
||||||
private String qrDescribe;
|
private String qrDescribe;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否创建携程订单(0:否,1:是)
|
||||||
|
*/
|
||||||
|
@Schema(description = "是否创建携程订单(0:否,1:是)")
|
||||||
|
private Integer enableCtripOrder;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程产品ID
|
||||||
|
*/
|
||||||
|
@Schema(description = "携程产品ID")
|
||||||
|
private Long ctripProductId;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.central.order.service;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程分销订单异步调用服务
|
||||||
|
*/
|
||||||
|
public interface ICtripDistOrderService {
|
||||||
|
/**
|
||||||
|
* 异步创建携程分销订单
|
||||||
|
*
|
||||||
|
* @param orderNo 本地订单号
|
||||||
|
* @param orderAmount 订单金额(分)
|
||||||
|
* @param ctripProductId 携程产品ID
|
||||||
|
* @param tenantId 租户ID
|
||||||
|
* @param mobile 用户手机号(可为null,为null时使用默认值)
|
||||||
|
*/
|
||||||
|
void createCtripDistOrder(String orderNo, String orderAmount, Long ctripProductId, String tenantId, String mobile);
|
||||||
|
}
|
||||||
+44
@@ -0,0 +1,44 @@
|
|||||||
|
package com.central.order.service.impl;
|
||||||
|
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import com.central.order.feign.CouponCenterService;
|
||||||
|
import com.central.order.service.ICtripDistOrderService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.scheduling.annotation.Async;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class CtripDistOrderServiceImpl implements ICtripDistOrderService {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CouponCenterService couponCenterService;
|
||||||
|
|
||||||
|
@Async
|
||||||
|
@Override
|
||||||
|
public void createCtripDistOrder(String orderNo, String orderAmount,
|
||||||
|
Long ctripProductId, String tenantId, String mobile) {
|
||||||
|
log.info("开始异步创建携程分销订单,orderNo: {}, mobile: {}", orderNo, mobile);
|
||||||
|
try {
|
||||||
|
Map<String, Object> params = new HashMap<>();
|
||||||
|
params.put("orderNo", orderNo);
|
||||||
|
params.put("orderAmount", orderAmount);
|
||||||
|
params.put("ctripProductId", ctripProductId);
|
||||||
|
params.put("tenantId", tenantId);
|
||||||
|
params.put("mobile", mobile);
|
||||||
|
|
||||||
|
Result<String> result = couponCenterService.createCtripDistOrder(params);
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- 二维码表添加携程分销相关字段
|
||||||
|
-- 用途:标识该二维码是否需要在支付成功后自动创建携程分销订单
|
||||||
|
ALTER TABLE qrcodes
|
||||||
|
ADD COLUMN enable_ctrip_order TINYINT(1) DEFAULT 0 COMMENT '是否创建携程订单(0:否,1:是)',
|
||||||
|
ADD COLUMN ctrip_product_id BIGINT DEFAULT NULL COMMENT '携程产品ID';
|
||||||
|
|
||||||
|
CREATE INDEX idx_qrcodes_enable_ctrip ON qrcodes(enable_ctrip_order);
|
||||||
@@ -122,5 +122,11 @@
|
|||||||
<artifactId>lombok</artifactId>
|
<artifactId>lombok</artifactId>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.httpcomponents</groupId>
|
||||||
|
<artifactId>httpclient</artifactId>
|
||||||
|
<version>4.5.14</version>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
+5
@@ -29,4 +29,9 @@ public interface ServiceNameConstants {
|
|||||||
* 消息中心服务
|
* 消息中心服务
|
||||||
*/
|
*/
|
||||||
String MSG_SERVICE = "msg-center";
|
String MSG_SERVICE = "msg-center";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 优惠券中心服务
|
||||||
|
*/
|
||||||
|
String COUPON_SERVICE = "coupon-center";
|
||||||
}
|
}
|
||||||
|
|||||||
+80
@@ -0,0 +1,80 @@
|
|||||||
|
package com.central.common.utils.http;
|
||||||
|
|
||||||
|
import org.apache.commons.codec.binary.Hex;
|
||||||
|
import org.apache.commons.codec.digest.DigestUtils;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author lishilin
|
||||||
|
* @see
|
||||||
|
* @since 1.0
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class HeaderUtils {
|
||||||
|
|
||||||
|
// @Value("${jetlinks.clientId}")
|
||||||
|
private String xClientId = "WFMfEGS8iHrEPRBH" ;
|
||||||
|
|
||||||
|
// @Value("${jetlinks.secureKey}")
|
||||||
|
private String secureKey = "ihat3zHC6T7xPZYFAEnG3tExQiFANd2n" ;
|
||||||
|
public Map<String, String> createHeadersOfParams(Map<String, Object> params) {
|
||||||
|
//时间戳
|
||||||
|
String xTimestamp = String.valueOf(System.currentTimeMillis());
|
||||||
|
//openApi客户端id
|
||||||
|
// String xClientId = "rN7cpmQb884W4hcH";
|
||||||
|
//密钥
|
||||||
|
// String secureKey = "hBYtiNxQrA8FZbtetGhCZJPi";
|
||||||
|
//将参数按ASCII排序后拼接为k1=v1&k2=v2的格式
|
||||||
|
String paramString = new TreeMap<>(params).entrySet()
|
||||||
|
.stream()
|
||||||
|
.map(e -> e.getKey().concat("=").concat(String.valueOf(e.getValue())))
|
||||||
|
.collect(Collectors.joining("&"));
|
||||||
|
|
||||||
|
System.out.println(paramString);
|
||||||
|
|
||||||
|
//param+X-Timestamp+SecureKey通过MD5加密
|
||||||
|
MessageDigest digest = DigestUtils.getMd5Digest();
|
||||||
|
System.out.println(paramString + xTimestamp + secureKey);
|
||||||
|
digest.update(paramString.getBytes());
|
||||||
|
digest.update(xTimestamp.getBytes());
|
||||||
|
digest.update(secureKey.getBytes());
|
||||||
|
|
||||||
|
Map<String, String> headers = new HashMap<>();
|
||||||
|
headers.put("X-Sign", Hex.encodeHexString(digest.digest()));
|
||||||
|
headers.put("X-Client-Id", xClientId);
|
||||||
|
headers.put("X-Timestamp", xTimestamp);
|
||||||
|
|
||||||
|
return headers;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public Map<String, String> createHeadersOfJsonString(String jsonString) {
|
||||||
|
//时间戳
|
||||||
|
String xTimestamp = String.valueOf(System.currentTimeMillis());
|
||||||
|
//openApi客户端id
|
||||||
|
// String xClientId = "rN7cpmQb884W4hcH";
|
||||||
|
//密钥
|
||||||
|
// String secureKey = "hBYtiNxQrA8FZbtetGhCZJPi";
|
||||||
|
|
||||||
|
|
||||||
|
//param+X-Timestamp+SecureKey通过MD5加密
|
||||||
|
MessageDigest digest = DigestUtils.getMd5Digest();
|
||||||
|
System.out.println(jsonString + xTimestamp + secureKey);
|
||||||
|
digest.update(jsonString.getBytes());
|
||||||
|
digest.update(xTimestamp.getBytes());
|
||||||
|
digest.update(secureKey.getBytes());
|
||||||
|
|
||||||
|
Map<String, String> headers = new HashMap<>(5);
|
||||||
|
headers.put("X-Sign", Hex.encodeHexString(digest.digest()));
|
||||||
|
headers.put("X-Client-Id", xClientId);
|
||||||
|
headers.put("X-Timestamp", xTimestamp);
|
||||||
|
|
||||||
|
return headers;
|
||||||
|
}
|
||||||
|
}
|
||||||
+39
@@ -0,0 +1,39 @@
|
|||||||
|
package com.central.common.utils.http;
|
||||||
|
|
||||||
|
import java.io.Closeable;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author wang
|
||||||
|
* @see
|
||||||
|
* @since 1.0
|
||||||
|
*/
|
||||||
|
public interface HttpRequest extends Closeable {
|
||||||
|
|
||||||
|
Response get() throws IOException;
|
||||||
|
|
||||||
|
Response post() throws IOException;
|
||||||
|
|
||||||
|
Response put() throws IOException;
|
||||||
|
|
||||||
|
Response delete() throws IOException;
|
||||||
|
|
||||||
|
Response patch() throws IOException;
|
||||||
|
|
||||||
|
HttpRequest encode(String encode);
|
||||||
|
|
||||||
|
HttpRequest contentType(String type);
|
||||||
|
|
||||||
|
HttpRequest param(String name, String value);
|
||||||
|
|
||||||
|
HttpRequest params(Map<String, Object> params);
|
||||||
|
|
||||||
|
HttpRequest header(String name, String value);
|
||||||
|
|
||||||
|
HttpRequest headers(Map<String, String> headers);
|
||||||
|
|
||||||
|
HttpRequest requestBody(String body);
|
||||||
|
|
||||||
|
HttpRequest resultAsJsonString();
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.central.common.utils.http;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author wang
|
||||||
|
* @see
|
||||||
|
* @since 1.0
|
||||||
|
*/
|
||||||
|
public interface Response {
|
||||||
|
|
||||||
|
byte[] asBytes() throws IOException;
|
||||||
|
}
|
||||||
+185
@@ -0,0 +1,185 @@
|
|||||||
|
package com.central.common.utils.http;
|
||||||
|
|
||||||
|
|
||||||
|
import org.apache.http.HttpResponse;
|
||||||
|
import org.apache.http.NameValuePair;
|
||||||
|
import org.apache.http.client.HttpClient;
|
||||||
|
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||||
|
import org.apache.http.client.methods.*;
|
||||||
|
import org.apache.http.entity.ContentType;
|
||||||
|
import org.apache.http.entity.StringEntity;
|
||||||
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
|
import org.apache.http.message.BasicNameValuePair;
|
||||||
|
import org.apache.http.util.EntityUtils;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.UnsupportedEncodingException;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author wang
|
||||||
|
* @see
|
||||||
|
* @since 1.0
|
||||||
|
*/
|
||||||
|
public class SimpleHttpRequest implements HttpRequest {
|
||||||
|
|
||||||
|
private Map<String, Object> params = new LinkedHashMap<>();
|
||||||
|
private Map<String, String> headers = new LinkedHashMap<>();
|
||||||
|
private String url;
|
||||||
|
private String requestBody;
|
||||||
|
private String contentType;
|
||||||
|
private String encode = "utf-8";
|
||||||
|
protected HttpClient httpClient;
|
||||||
|
|
||||||
|
public SimpleHttpRequest(String url) {
|
||||||
|
this.url = url;
|
||||||
|
createHttpClient();
|
||||||
|
}
|
||||||
|
|
||||||
|
public SimpleHttpRequest(String url, HttpClient client) {
|
||||||
|
this.url = url;
|
||||||
|
this.httpClient = client;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void createHttpClient() {
|
||||||
|
if (httpClient == null) {
|
||||||
|
HttpClientBuilder builder = HttpClientBuilder.create();
|
||||||
|
httpClient = builder.build();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Response get() throws IOException {
|
||||||
|
String param = EntityUtils.toString(createUrlEncodedFormEntity());
|
||||||
|
String tmpUrl = url + (url.contains("?") ? "&" : "?") + param;
|
||||||
|
HttpGet get = new HttpGet(tmpUrl);
|
||||||
|
HttpResponse response = execute(get);
|
||||||
|
return getResultValue(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Response post() throws IOException {
|
||||||
|
HttpPost post = new HttpPost(url);
|
||||||
|
if (requestBody != null)
|
||||||
|
post.setEntity(new StringEntity(requestBody, ContentType.create(contentType,encode)));
|
||||||
|
else {
|
||||||
|
post.setEntity(createUrlEncodedFormEntity());
|
||||||
|
}
|
||||||
|
HttpResponse response = execute(post);
|
||||||
|
return getResultValue(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Response put() throws IOException {
|
||||||
|
HttpPut put = new HttpPut(url);
|
||||||
|
if (requestBody != null)
|
||||||
|
put.setEntity(new StringEntity(requestBody, ContentType.create(contentType, encode)));
|
||||||
|
else {
|
||||||
|
|
||||||
|
put.setEntity(createUrlEncodedFormEntity());
|
||||||
|
}
|
||||||
|
HttpResponse response = execute(put);
|
||||||
|
return getResultValue(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected UrlEncodedFormEntity createUrlEncodedFormEntity() throws UnsupportedEncodingException {
|
||||||
|
List<NameValuePair> nameValuePair = params.entrySet()
|
||||||
|
.stream().map(stringStringEntry ->
|
||||||
|
new BasicNameValuePair(stringStringEntry.getKey(), String.valueOf(stringStringEntry.getValue())))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
return new UrlEncodedFormEntity(nameValuePair, encode);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Response delete() throws IOException {
|
||||||
|
HttpDelete delete = new HttpDelete(url);
|
||||||
|
HttpResponse response = execute(delete);
|
||||||
|
return getResultValue(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Response patch() throws IOException {
|
||||||
|
HttpPatch delete = new HttpPatch(url);
|
||||||
|
if (requestBody != null)
|
||||||
|
delete.setEntity(new StringEntity(requestBody, ContentType.create(contentType)));
|
||||||
|
else {
|
||||||
|
delete.setEntity(createUrlEncodedFormEntity());
|
||||||
|
}
|
||||||
|
return getResultValue(execute(delete));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() throws IOException {
|
||||||
|
if (httpClient != null && httpClient instanceof CloseableHttpClient) {
|
||||||
|
((CloseableHttpClient) httpClient).close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public HttpRequest resultAsJsonString() {
|
||||||
|
header("Accept", "application/json");
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public HttpRequest requestBody(String body) {
|
||||||
|
contentType("application/json");
|
||||||
|
this.requestBody = body;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public HttpRequest encode(String encode) {
|
||||||
|
this.encode = encode;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public HttpRequest contentType(String type) {
|
||||||
|
this.contentType = type;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public HttpRequest param(String name, String value) {
|
||||||
|
this.params.put(name, value);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public HttpRequest params(Map<String, Object> params) {
|
||||||
|
this.params.putAll(params);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public HttpRequest header(String name, String value) {
|
||||||
|
this.headers.put(name, value);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public HttpRequest headers(Map<String, String> header) {
|
||||||
|
this.headers.putAll(header);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Response getResultValue(HttpResponse res) throws IOException {
|
||||||
|
return new SimpleResponse(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
private HttpResponse execute(HttpRequestBase request) throws IOException {
|
||||||
|
putHeader(request);
|
||||||
|
return httpClient.execute(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void putHeader(HttpUriRequest request) {
|
||||||
|
headers.forEach(request::setHeader);
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
package com.central.common.utils.http;
|
||||||
|
|
||||||
|
import org.apache.http.HttpResponse;
|
||||||
|
import org.apache.http.util.EntityUtils;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author wang
|
||||||
|
* @see
|
||||||
|
* @since 1.0
|
||||||
|
*/
|
||||||
|
public class SimpleResponse implements Response {
|
||||||
|
|
||||||
|
HttpResponse response;
|
||||||
|
|
||||||
|
public SimpleResponse(HttpResponse response) {
|
||||||
|
this.response = response;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] asBytes() throws IOException {
|
||||||
|
return EntityUtils.toByteArray(response.getEntity());
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -42,6 +42,8 @@ export default [
|
|||||||
{ path: '/orders/ctripOrder.html', component: '@/pages/orders/CtripOrder' },
|
{ path: '/orders/ctripOrder.html', component: '@/pages/orders/CtripOrder' },
|
||||||
// 携程退款管理
|
// 携程退款管理
|
||||||
{ path: '/orders/ctripRefund.html', component: '@/pages/orders/CtripRefund' },
|
{ path: '/orders/ctripRefund.html', component: '@/pages/orders/CtripRefund' },
|
||||||
|
// 携程分销订单管理
|
||||||
|
{ path: '/orders/ctripDistOrder.html', component: '@/pages/orders/CtripDistOrder' },
|
||||||
// 订单状态超时监控配置
|
// 订单状态超时监控配置
|
||||||
{ path: '/orders/statusTimeoutConfig.html', component: '@/pages/orders/StatusTimeoutConfig' },
|
{ path: '/orders/statusTimeoutConfig.html', component: '@/pages/orders/StatusTimeoutConfig' },
|
||||||
],
|
],
|
||||||
|
|||||||
Binary file not shown.
+404
-157
@@ -1,27 +1,24 @@
|
|||||||
import React, { useState, useCallback, useRef } from 'react';
|
import React, { useState, useCallback, useRef, useEffect } from 'react';
|
||||||
import {
|
import {
|
||||||
Modal,
|
Modal,
|
||||||
Upload,
|
|
||||||
Button,
|
Button,
|
||||||
Progress,
|
Progress,
|
||||||
List,
|
|
||||||
Typography,
|
Typography,
|
||||||
Space,
|
Space,
|
||||||
Alert,
|
Alert,
|
||||||
message,
|
message,
|
||||||
Spin,
|
|
||||||
Tag,
|
|
||||||
Result,
|
Result,
|
||||||
|
Tabs,
|
||||||
|
Badge,
|
||||||
} from 'antd';
|
} from 'antd';
|
||||||
import {
|
import {
|
||||||
InboxOutlined,
|
|
||||||
FileOutlined,
|
|
||||||
CheckCircleOutlined,
|
CheckCircleOutlined,
|
||||||
CloseCircleOutlined,
|
CloseCircleOutlined,
|
||||||
LoadingOutlined,
|
LoadingOutlined,
|
||||||
FolderOpenOutlined,
|
FolderOpenOutlined,
|
||||||
|
FileOutlined,
|
||||||
|
ReloadOutlined,
|
||||||
} from '@ant-design/icons';
|
} from '@ant-design/icons';
|
||||||
import type { UploadFile } from 'antd/es/upload/interface';
|
|
||||||
import {
|
import {
|
||||||
uploadSingleFile,
|
uploadSingleFile,
|
||||||
completeUpload,
|
completeUpload,
|
||||||
@@ -29,8 +26,7 @@ import {
|
|||||||
} from '@/services/threeDModel';
|
} from '@/services/threeDModel';
|
||||||
import styles from './ModelUploadModal.less';
|
import styles from './ModelUploadModal.less';
|
||||||
|
|
||||||
const { Dragger } = Upload;
|
const { Text } = Typography;
|
||||||
const { Text, Paragraph } = Typography;
|
|
||||||
|
|
||||||
interface ModelUploadModalProps {
|
interface ModelUploadModalProps {
|
||||||
visible: boolean;
|
visible: boolean;
|
||||||
@@ -39,152 +35,262 @@ interface ModelUploadModalProps {
|
|||||||
onComplete: () => void;
|
onComplete: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface FileUploadItem {
|
interface FileItem {
|
||||||
file: File;
|
file: File;
|
||||||
relativePath: string;
|
relativePath: string;
|
||||||
status: 'pending' | 'uploading' | 'success' | 'error';
|
|
||||||
progress: number;
|
|
||||||
url?: string;
|
|
||||||
error?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type FileStatus = 'pending' | 'uploading' | 'success' | 'error';
|
||||||
|
|
||||||
|
// 虚拟列表配置
|
||||||
|
const ITEM_HEIGHT = 44;
|
||||||
|
const CONTAINER_HEIGHT = 400;
|
||||||
|
const VISIBLE_COUNT = Math.ceil(CONTAINER_HEIGHT / ITEM_HEIGHT);
|
||||||
|
const BUFFER = 5;
|
||||||
|
|
||||||
|
// 并发上传数
|
||||||
|
const CONCURRENCY = 5;
|
||||||
|
|
||||||
const ModelUploadModal: React.FC<ModelUploadModalProps> = ({
|
const ModelUploadModal: React.FC<ModelUploadModalProps> = ({
|
||||||
visible,
|
visible,
|
||||||
model,
|
model,
|
||||||
onCancel,
|
onCancel,
|
||||||
onComplete,
|
onComplete,
|
||||||
}) => {
|
}) => {
|
||||||
const [fileList, setFileList] = useState<FileUploadItem[]>([]);
|
|
||||||
const [uploading, setUploading] = useState(false);
|
const [uploading, setUploading] = useState(false);
|
||||||
const [uploadComplete, setUploadComplete] = useState(false);
|
const [uploadComplete, setUploadComplete] = useState(false);
|
||||||
const [overallProgress, setOverallProgress] = useState(0);
|
const [overallProgress, setOverallProgress] = useState(0);
|
||||||
|
const [scrollTop, setScrollTop] = useState(0);
|
||||||
|
const [stats, setStats] = useState({ total: 0, success: 0, error: 0 });
|
||||||
|
const [activeTab, setActiveTab] = useState<'all' | 'failed'>('all');
|
||||||
|
const [, setRenderTick] = useState(0);
|
||||||
|
|
||||||
|
const filesRef = useRef<FileItem[]>([]);
|
||||||
|
const statusRef = useRef<Map<number, FileStatus>>(new Map());
|
||||||
|
const progressRef = useRef<Map<number, number>>(new Map());
|
||||||
|
const errorRef = useRef<Map<number, string>>(new Map());
|
||||||
const abortRef = useRef(false);
|
const abortRef = useRef(false);
|
||||||
|
const successCountRef = useRef(0);
|
||||||
|
const failCountRef = useRef(0);
|
||||||
|
const tickTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||||
|
const uploadStartedRef = useRef(false);
|
||||||
|
|
||||||
|
const startRenderTick = () => {
|
||||||
|
tickTimerRef.current = setInterval(() => {
|
||||||
|
setRenderTick((t) => t + 1);
|
||||||
|
}, 200);
|
||||||
|
};
|
||||||
|
|
||||||
|
const stopRenderTick = () => {
|
||||||
|
if (tickTimerRef.current) {
|
||||||
|
clearInterval(tickTimerRef.current);
|
||||||
|
tickTimerRef.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return () => stopRenderTick();
|
||||||
|
}, []);
|
||||||
|
|
||||||
// 重置状态
|
|
||||||
const resetState = () => {
|
const resetState = () => {
|
||||||
setFileList([]);
|
filesRef.current = [];
|
||||||
|
statusRef.current = new Map();
|
||||||
|
progressRef.current = new Map();
|
||||||
|
errorRef.current = new Map();
|
||||||
|
abortRef.current = false;
|
||||||
|
successCountRef.current = 0;
|
||||||
|
failCountRef.current = 0;
|
||||||
|
uploadStartedRef.current = false;
|
||||||
|
stopRenderTick();
|
||||||
setUploading(false);
|
setUploading(false);
|
||||||
setUploadComplete(false);
|
setUploadComplete(false);
|
||||||
setOverallProgress(0);
|
setOverallProgress(0);
|
||||||
abortRef.current = false;
|
setScrollTop(0);
|
||||||
|
setActiveTab('all');
|
||||||
|
setStats({ total: 0, success: 0, error: 0 });
|
||||||
|
setRenderTick(0);
|
||||||
};
|
};
|
||||||
|
|
||||||
// 处理文件夹选择
|
|
||||||
const handleFolderSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
const handleFolderSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
const files = e.target.files;
|
const files = e.target.files;
|
||||||
if (!files || files.length === 0) return;
|
if (!files || files.length === 0) return;
|
||||||
|
|
||||||
const items: FileUploadItem[] = [];
|
const items: FileItem[] = [];
|
||||||
for (let i = 0; i < files.length; i++) {
|
for (let i = 0; i < files.length; i++) {
|
||||||
const file = files[i];
|
const file = files[i];
|
||||||
// webkitRelativePath 包含完整的相对路径
|
|
||||||
const relativePath = (file as any).webkitRelativePath || file.name;
|
const relativePath = (file as any).webkitRelativePath || file.name;
|
||||||
items.push({
|
items.push({ file, relativePath });
|
||||||
file,
|
|
||||||
relativePath,
|
|
||||||
status: 'pending',
|
|
||||||
progress: 0,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查是否包含tileset.json
|
|
||||||
const hasTileset = items.some(
|
const hasTileset = items.some(
|
||||||
(item) =>
|
(item) =>
|
||||||
item.relativePath.endsWith('tileset.json') &&
|
item.relativePath.endsWith('tileset.json') &&
|
||||||
!item.relativePath.includes('/Block/')
|
!item.relativePath.includes('/Block/'),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!hasTileset) {
|
if (!hasTileset) {
|
||||||
message.warning('未检测到根目录下的tileset.json文件,请确保选择了正确的3D Tiles文件夹');
|
message.warning('未检测到根目录下的tileset.json文件,请确保选择了正确的3D Tiles文件夹');
|
||||||
}
|
}
|
||||||
|
|
||||||
setFileList(items);
|
filesRef.current = items;
|
||||||
|
statusRef.current = new Map();
|
||||||
|
progressRef.current = new Map();
|
||||||
|
errorRef.current = new Map();
|
||||||
|
successCountRef.current = 0;
|
||||||
|
failCountRef.current = 0;
|
||||||
|
uploadStartedRef.current = false;
|
||||||
|
|
||||||
|
setStats({ total: items.length, success: 0, error: 0 });
|
||||||
|
setActiveTab('all');
|
||||||
setUploadComplete(false);
|
setUploadComplete(false);
|
||||||
|
setScrollTop(0);
|
||||||
|
setRenderTick((t) => t + 1);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// 开始上传
|
|
||||||
const handleUpload = async () => {
|
const handleUpload = async () => {
|
||||||
if (!model?.id || fileList.length === 0) {
|
if (!model?.id || filesRef.current.length === 0) {
|
||||||
message.error('请先选择文件');
|
message.error('请先选择文件');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setUploading(true);
|
setUploading(true);
|
||||||
|
uploadStartedRef.current = true;
|
||||||
abortRef.current = false;
|
abortRef.current = false;
|
||||||
|
successCountRef.current = 0;
|
||||||
|
failCountRef.current = 0;
|
||||||
|
|
||||||
let successCount = 0;
|
const files = filesRef.current;
|
||||||
let failCount = 0;
|
const total = files.length;
|
||||||
|
const sharedIndex = { value: 0 };
|
||||||
|
|
||||||
// 更新文件列表
|
startRenderTick();
|
||||||
const updateFileStatus = (
|
|
||||||
index: number,
|
const worker = async () => {
|
||||||
status: FileUploadItem['status'],
|
while (sharedIndex.value < total && !abortRef.current) {
|
||||||
progress: number,
|
const i = sharedIndex.value++;
|
||||||
url?: string,
|
const item = files[i];
|
||||||
error?: string
|
|
||||||
) => {
|
statusRef.current.set(i, 'uploading');
|
||||||
setFileList((prev) => {
|
progressRef.current.set(i, 0);
|
||||||
const newList = [...prev];
|
|
||||||
newList[index] = { ...newList[index], status, progress, url, error };
|
try {
|
||||||
return newList;
|
const result = await uploadSingleFile(
|
||||||
});
|
model.id,
|
||||||
|
item.file,
|
||||||
|
item.relativePath,
|
||||||
|
(percent) => {
|
||||||
|
progressRef.current.set(i, percent);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.resp_code === 0) {
|
||||||
|
statusRef.current.set(i, 'success');
|
||||||
|
successCountRef.current++;
|
||||||
|
} else {
|
||||||
|
throw new Error(result.resp_msg || '上传失败');
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
statusRef.current.set(i, 'error');
|
||||||
|
errorRef.current.set(i, err.message);
|
||||||
|
failCountRef.current++;
|
||||||
|
}
|
||||||
|
|
||||||
|
const done = successCountRef.current + failCountRef.current;
|
||||||
|
setOverallProgress(Math.round((done / total) * 100));
|
||||||
|
|
||||||
|
if (done % 20 === 0 || done === total) {
|
||||||
|
setStats({
|
||||||
|
total,
|
||||||
|
success: successCountRef.current,
|
||||||
|
error: failCountRef.current,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 逐个上传文件
|
await Promise.all(Array.from({ length: CONCURRENCY }, worker));
|
||||||
for (let i = 0; i < fileList.length; i++) {
|
|
||||||
if (abortRef.current) break;
|
|
||||||
|
|
||||||
const item = fileList[i];
|
stopRenderTick();
|
||||||
updateFileStatus(i, 'uploading', 0);
|
|
||||||
|
|
||||||
try {
|
const finalSuccess = successCountRef.current;
|
||||||
const result = await uploadSingleFile(
|
const finalFail = failCountRef.current;
|
||||||
model.id,
|
setStats({ total, success: finalSuccess, error: finalFail });
|
||||||
item.file,
|
setRenderTick((t) => t + 1);
|
||||||
item.relativePath,
|
|
||||||
(percent) => {
|
|
||||||
updateFileStatus(i, 'uploading', percent);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
if (result.resp_code === 0) {
|
if (finalSuccess === total) {
|
||||||
updateFileStatus(i, 'success', 100, result.datas);
|
|
||||||
successCount++;
|
|
||||||
} else {
|
|
||||||
throw new Error(result.resp_msg || '上传失败');
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
updateFileStatus(i, 'error', 0, undefined, error.message);
|
|
||||||
failCount++;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 更新总进度
|
|
||||||
setOverallProgress(Math.round(((i + 1) / fileList.length) * 100));
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果全部成功,调用完成接口
|
|
||||||
if (successCount === fileList.length) {
|
|
||||||
try {
|
try {
|
||||||
await completeUpload(model.id);
|
await completeUpload(model.id);
|
||||||
message.success('所有文件上传完成!');
|
message.success('所有文件上传完成!');
|
||||||
setUploadComplete(true);
|
setUploadComplete(true);
|
||||||
} catch (error) {
|
} catch {
|
||||||
message.error('更新状态失败');
|
message.error('更新状态失败');
|
||||||
}
|
}
|
||||||
} else if (failCount > 0) {
|
} else if (finalFail > 0) {
|
||||||
message.warning(`上传完成,成功 ${successCount} 个,失败 ${failCount} 个`);
|
// 自动切到失败列表,方便用户逐个重试
|
||||||
|
setActiveTab('failed');
|
||||||
|
message.warning(`上传完成,成功 ${finalSuccess} 个,失败 ${finalFail} 个`);
|
||||||
}
|
}
|
||||||
|
|
||||||
setUploading(false);
|
setUploading(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
// 取消上传
|
// 重试单个失败文件
|
||||||
|
const handleRetryFile = async (index: number) => {
|
||||||
|
if (!model?.id || uploading) return;
|
||||||
|
const item = filesRef.current[index];
|
||||||
|
if (!item) return;
|
||||||
|
|
||||||
|
statusRef.current.set(index, 'uploading');
|
||||||
|
progressRef.current.set(index, 0);
|
||||||
|
errorRef.current.delete(index);
|
||||||
|
failCountRef.current = Math.max(0, failCountRef.current - 1);
|
||||||
|
setRenderTick((t) => t + 1);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await uploadSingleFile(
|
||||||
|
model.id,
|
||||||
|
item.file,
|
||||||
|
item.relativePath,
|
||||||
|
(percent) => {
|
||||||
|
progressRef.current.set(index, percent);
|
||||||
|
setRenderTick((t) => t + 1);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.resp_code === 0) {
|
||||||
|
statusRef.current.set(index, 'success');
|
||||||
|
successCountRef.current++;
|
||||||
|
} else {
|
||||||
|
throw new Error(result.resp_msg || '上传失败');
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
statusRef.current.set(index, 'error');
|
||||||
|
errorRef.current.set(index, err.message);
|
||||||
|
failCountRef.current++;
|
||||||
|
}
|
||||||
|
|
||||||
|
const total = filesRef.current.length;
|
||||||
|
const newSuccess = successCountRef.current;
|
||||||
|
const newFail = failCountRef.current;
|
||||||
|
setStats({ total, success: newSuccess, error: newFail });
|
||||||
|
setRenderTick((t) => t + 1);
|
||||||
|
|
||||||
|
// 全部成功时自动完成
|
||||||
|
if (newSuccess === total && newFail === 0) {
|
||||||
|
try {
|
||||||
|
await completeUpload(model.id);
|
||||||
|
message.success('所有文件上传完成!');
|
||||||
|
setUploadComplete(true);
|
||||||
|
} catch {
|
||||||
|
message.error('更新状态失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleAbort = () => {
|
const handleAbort = () => {
|
||||||
abortRef.current = true;
|
abortRef.current = true;
|
||||||
message.info('正在取消上传...');
|
message.info('正在取消上传...');
|
||||||
};
|
};
|
||||||
|
|
||||||
// 关闭弹窗
|
|
||||||
const handleClose = () => {
|
const handleClose = () => {
|
||||||
if (uploading) {
|
if (uploading) {
|
||||||
Modal.confirm({
|
Modal.confirm({
|
||||||
@@ -208,16 +314,6 @@ const ModelUploadModal: React.FC<ModelUploadModalProps> = ({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 统计信息
|
|
||||||
const stats = {
|
|
||||||
total: fileList.length,
|
|
||||||
success: fileList.filter((f) => f.status === 'success').length,
|
|
||||||
error: fileList.filter((f) => f.status === 'error').length,
|
|
||||||
pending: fileList.filter((f) => f.status === 'pending').length,
|
|
||||||
uploading: fileList.filter((f) => f.status === 'uploading').length,
|
|
||||||
totalSize: fileList.reduce((sum, f) => sum + f.file.size, 0),
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatSize = (bytes: number) => {
|
const formatSize = (bytes: number) => {
|
||||||
if (bytes === 0) return '0 B';
|
if (bytes === 0) return '0 B';
|
||||||
const k = 1024;
|
const k = 1024;
|
||||||
@@ -226,6 +322,127 @@ const ModelUploadModal: React.FC<ModelUploadModalProps> = ({
|
|||||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 全部文件的虚拟列表计算
|
||||||
|
const files = filesRef.current;
|
||||||
|
const totalCount = files.length;
|
||||||
|
const startIndex = Math.max(0, Math.floor(scrollTop / ITEM_HEIGHT) - BUFFER);
|
||||||
|
const endIndex = Math.min(totalCount - 1, startIndex + VISIBLE_COUNT + BUFFER * 2);
|
||||||
|
|
||||||
|
const visibleItems = files.slice(startIndex, endIndex + 1).map((item, offset) => {
|
||||||
|
const idx = startIndex + offset;
|
||||||
|
return {
|
||||||
|
index: idx,
|
||||||
|
file: item.file,
|
||||||
|
relativePath: item.relativePath,
|
||||||
|
status: statusRef.current.get(idx) ?? ('pending' as FileStatus),
|
||||||
|
progress: progressRef.current.get(idx) ?? 0,
|
||||||
|
error: errorRef.current.get(idx),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// 失败文件列表(直接从 statusRef 收集,无需虚拟列表)
|
||||||
|
const failedItems: Array<{
|
||||||
|
index: number;
|
||||||
|
file: File;
|
||||||
|
relativePath: string;
|
||||||
|
error: string;
|
||||||
|
status: FileStatus;
|
||||||
|
progress: number;
|
||||||
|
}> = [];
|
||||||
|
statusRef.current.forEach((status, idx) => {
|
||||||
|
if (status === 'error' || status === 'uploading') {
|
||||||
|
const f = filesRef.current[idx];
|
||||||
|
if (f) {
|
||||||
|
failedItems.push({
|
||||||
|
index: idx,
|
||||||
|
file: f.file,
|
||||||
|
relativePath: f.relativePath,
|
||||||
|
error: errorRef.current.get(idx) ?? '',
|
||||||
|
status,
|
||||||
|
progress: progressRef.current.get(idx) ?? 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
failedItems.sort((a, b) => a.index - b.index);
|
||||||
|
|
||||||
|
const totalSize = files.reduce((sum, f) => sum + f.file.size, 0);
|
||||||
|
|
||||||
|
const getStatusIcon = (status: FileStatus) => {
|
||||||
|
switch (status) {
|
||||||
|
case 'uploading':
|
||||||
|
return <LoadingOutlined spin style={{ color: '#1890ff' }} />;
|
||||||
|
case 'success':
|
||||||
|
return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
|
||||||
|
case 'error':
|
||||||
|
return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
|
||||||
|
default:
|
||||||
|
return <FileOutlined style={{ color: '#bfbfbf' }} />;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderFileRow = (item: {
|
||||||
|
index: number;
|
||||||
|
file: File;
|
||||||
|
relativePath: string;
|
||||||
|
status: FileStatus;
|
||||||
|
progress: number;
|
||||||
|
error?: string;
|
||||||
|
}) => (
|
||||||
|
<div
|
||||||
|
key={item.index}
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
padding: '0 12px',
|
||||||
|
height: ITEM_HEIGHT,
|
||||||
|
borderBottom: '1px solid #f5f5f5',
|
||||||
|
fontSize: 13,
|
||||||
|
background: '#fff',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Space size={6} style={{ flex: 1, minWidth: 0 }}>
|
||||||
|
{getStatusIcon(item.status)}
|
||||||
|
<Text
|
||||||
|
ellipsis={{ tooltip: item.relativePath }}
|
||||||
|
style={{ maxWidth: 420, fontSize: 13 }}
|
||||||
|
>
|
||||||
|
{item.relativePath}
|
||||||
|
</Text>
|
||||||
|
</Space>
|
||||||
|
<div style={{ flexShrink: 0, marginLeft: 8, textAlign: 'right' }}>
|
||||||
|
{item.status === 'uploading' ? (
|
||||||
|
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||||
|
{item.progress}%
|
||||||
|
</Text>
|
||||||
|
) : item.status === 'error' ? (
|
||||||
|
<Space size={4}>
|
||||||
|
<Text
|
||||||
|
type="danger"
|
||||||
|
style={{ fontSize: 12, maxWidth: 140, display: 'inline-block' }}
|
||||||
|
ellipsis={{ tooltip: item.error }}
|
||||||
|
>
|
||||||
|
{item.error}
|
||||||
|
</Text>
|
||||||
|
<Button
|
||||||
|
type="link"
|
||||||
|
size="small"
|
||||||
|
icon={<ReloadOutlined />}
|
||||||
|
disabled={uploading}
|
||||||
|
onClick={() => handleRetryFile(item.index)}
|
||||||
|
style={{ padding: '0 4px', fontSize: 12 }}
|
||||||
|
title="重试上传"
|
||||||
|
/>
|
||||||
|
</Space>
|
||||||
|
) : (
|
||||||
|
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||||
|
{formatSize(item.file.size)}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
title={`上传模型文件 - ${model?.modelName || ''}`}
|
title={`上传模型文件 - ${model?.modelName || ''}`}
|
||||||
@@ -240,7 +457,7 @@ const ModelUploadModal: React.FC<ModelUploadModalProps> = ({
|
|||||||
) : (
|
) : (
|
||||||
<Space>
|
<Space>
|
||||||
<Button onClick={handleClose}>{uploading ? '取消' : '关闭'}</Button>
|
<Button onClick={handleClose}>{uploading ? '取消' : '关闭'}</Button>
|
||||||
{!uploading && fileList.length > 0 && (
|
{!uploading && totalCount > 0 && !uploadStartedRef.current && (
|
||||||
<Button type="primary" onClick={handleUpload}>
|
<Button type="primary" onClick={handleUpload}>
|
||||||
开始上传
|
开始上传
|
||||||
</Button>
|
</Button>
|
||||||
@@ -260,12 +477,12 @@ const ModelUploadModal: React.FC<ModelUploadModalProps> = ({
|
|||||||
<Result
|
<Result
|
||||||
status="success"
|
status="success"
|
||||||
title="上传完成"
|
title="上传完成"
|
||||||
subTitle={`成功上传 ${stats.success} 个文件,共 ${formatSize(stats.totalSize)}`}
|
subTitle={`成功上传 ${stats.success} 个文件,共 ${formatSize(totalSize)}`}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
{/* 文件选择区域 */}
|
{/* 文件选择区域 */}
|
||||||
{fileList.length === 0 && (
|
{totalCount === 0 && (
|
||||||
<div className={styles.selectArea}>
|
<div className={styles.selectArea}>
|
||||||
<Alert
|
<Alert
|
||||||
message="请选择3D Tiles模型文件夹"
|
message="请选择3D Tiles模型文件夹"
|
||||||
@@ -297,19 +514,23 @@ const ModelUploadModal: React.FC<ModelUploadModalProps> = ({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* 文件列表 */}
|
{/* 文件列表 */}
|
||||||
{fileList.length > 0 && (
|
{totalCount > 0 && (
|
||||||
<>
|
<>
|
||||||
{/* 统计信息 */}
|
{/* 统计信息 */}
|
||||||
<div className={styles.statsBar}>
|
<div className={styles.statsBar}>
|
||||||
<Space split={<span style={{ color: '#d9d9d9' }}>|</span>}>
|
<Space split={<span style={{ color: '#d9d9d9' }}>|</span>}>
|
||||||
<Text>共 {stats.total} 个文件</Text>
|
<Text>共 {stats.total} 个文件</Text>
|
||||||
<Text>总大小 {formatSize(stats.totalSize)}</Text>
|
<Text>总大小 {formatSize(totalSize)}</Text>
|
||||||
{stats.success > 0 && (
|
{stats.success > 0 && (
|
||||||
<Text type="success">成功 {stats.success}</Text>
|
<Text type="success">成功 {stats.success}</Text>
|
||||||
)}
|
)}
|
||||||
{stats.error > 0 && <Text type="danger">失败 {stats.error}</Text>}
|
{stats.error > 0 && (
|
||||||
{stats.uploading > 0 && (
|
<Text type="danger">失败 {stats.error}</Text>
|
||||||
<Text type="warning">上传中 {stats.uploading}</Text>
|
)}
|
||||||
|
{uploading && (
|
||||||
|
<Text type="warning">
|
||||||
|
剩余 {stats.total - stats.success - stats.error}
|
||||||
|
</Text>
|
||||||
)}
|
)}
|
||||||
</Space>
|
</Space>
|
||||||
</div>
|
</div>
|
||||||
@@ -319,67 +540,93 @@ const ModelUploadModal: React.FC<ModelUploadModalProps> = ({
|
|||||||
<Progress
|
<Progress
|
||||||
percent={overallProgress}
|
percent={overallProgress}
|
||||||
status="active"
|
status="active"
|
||||||
strokeColor={{
|
strokeColor={{ '0%': '#108ee9', '100%': '#87d068' }}
|
||||||
'0%': '#108ee9',
|
style={{ marginBottom: 8 }}
|
||||||
'100%': '#87d068',
|
|
||||||
}}
|
|
||||||
style={{ marginBottom: 16 }}
|
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* 文件列表 */}
|
{/* Tab:全部文件 / 失败文件 */}
|
||||||
<div className={styles.fileList}>
|
<Tabs
|
||||||
<List
|
activeKey={activeTab}
|
||||||
size="small"
|
onChange={(key) => {
|
||||||
dataSource={fileList}
|
setActiveTab(key as 'all' | 'failed');
|
||||||
renderItem={(item, index) => (
|
setScrollTop(0);
|
||||||
<List.Item
|
}}
|
||||||
className={`${styles.fileItem} ${styles[item.status]}`}
|
size="small"
|
||||||
>
|
style={{ marginBottom: 0 }}
|
||||||
<div className={styles.fileInfo}>
|
items={[
|
||||||
<Space>
|
{
|
||||||
{item.status === 'pending' && <FileOutlined />}
|
key: 'all',
|
||||||
{item.status === 'uploading' && (
|
label: `全部文件 (${totalCount})`,
|
||||||
<LoadingOutlined spin />
|
children: (
|
||||||
)}
|
<div
|
||||||
{item.status === 'success' && (
|
style={{
|
||||||
<CheckCircleOutlined style={{ color: '#52c41a' }} />
|
height: CONTAINER_HEIGHT,
|
||||||
)}
|
overflow: 'auto',
|
||||||
{item.status === 'error' && (
|
border: '1px solid #f0f0f0',
|
||||||
<CloseCircleOutlined style={{ color: '#ff4d4f' }} />
|
borderRadius: 4,
|
||||||
)}
|
}}
|
||||||
<Text
|
onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}
|
||||||
ellipsis={{ tooltip: item.relativePath }}
|
>
|
||||||
style={{ maxWidth: 400 }}
|
<div style={{ height: totalCount * ITEM_HEIGHT, position: 'relative' }}>
|
||||||
>
|
{visibleItems.map((item) => (
|
||||||
{item.relativePath}
|
<div
|
||||||
</Text>
|
key={item.index}
|
||||||
</Space>
|
style={{
|
||||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
position: 'absolute',
|
||||||
{formatSize(item.file.size)}
|
top: item.index * ITEM_HEIGHT,
|
||||||
</Text>
|
left: 0,
|
||||||
|
right: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{renderFileRow(item)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{item.status === 'uploading' && (
|
),
|
||||||
<Progress
|
},
|
||||||
percent={item.progress}
|
{
|
||||||
size="small"
|
key: 'failed',
|
||||||
style={{ width: 100 }}
|
label: (
|
||||||
/>
|
<Badge count={stats.error} size="small" offset={[6, -2]}>
|
||||||
)}
|
<span style={{ paddingRight: stats.error > 0 ? 12 : 0 }}>失败文件</span>
|
||||||
{item.status === 'error' && (
|
</Badge>
|
||||||
<Text type="danger" style={{ fontSize: 12 }}>
|
),
|
||||||
{item.error}
|
children:
|
||||||
</Text>
|
failedItems.length === 0 ? (
|
||||||
)}
|
<div
|
||||||
</List.Item>
|
style={{
|
||||||
)}
|
height: CONTAINER_HEIGHT,
|
||||||
style={{ maxHeight: 400, overflow: 'auto' }}
|
display: 'flex',
|
||||||
/>
|
alignItems: 'center',
|
||||||
</div>
|
justifyContent: 'center',
|
||||||
|
color: '#bfbfbf',
|
||||||
|
border: '1px solid #f0f0f0',
|
||||||
|
borderRadius: 4,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
暂无失败文件
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
height: CONTAINER_HEIGHT,
|
||||||
|
overflow: 'auto',
|
||||||
|
border: '1px solid #f0f0f0',
|
||||||
|
borderRadius: 4,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{failedItems.map((item) => renderFileRow(item))}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* 重新选择 */}
|
{/* 重新选择 */}
|
||||||
{!uploading && (
|
{!uploading && (
|
||||||
<div style={{ marginTop: 16, textAlign: 'center' }}>
|
<div style={{ marginTop: 8, textAlign: 'center' }}>
|
||||||
<input
|
<input
|
||||||
type="file"
|
type="file"
|
||||||
id="folderInputReset"
|
id="folderInputReset"
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Tag } from 'antd';
|
||||||
|
import {
|
||||||
|
CTRIP_DIST_ORDER_STATUS_OPTIONS,
|
||||||
|
CONSUME_STATUS_OPTIONS,
|
||||||
|
REFUND_STATUS_OPTIONS,
|
||||||
|
findLabel,
|
||||||
|
findColor,
|
||||||
|
} from './constants';
|
||||||
|
|
||||||
|
export const CtripDistOrderStatusTag: React.FC<{ value?: string }> = ({ value }) => {
|
||||||
|
const label = findLabel(CTRIP_DIST_ORDER_STATUS_OPTIONS, value);
|
||||||
|
const color = findColor(CTRIP_DIST_ORDER_STATUS_OPTIONS, value);
|
||||||
|
return <Tag color={color}>{label}</Tag>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ConsumeStatusTag: React.FC<{ value?: number }> = ({ value }) => {
|
||||||
|
const label = findLabel(CONSUME_STATUS_OPTIONS, value);
|
||||||
|
const color = findColor(CONSUME_STATUS_OPTIONS, value);
|
||||||
|
return <Tag color={color}>{label}</Tag>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const RefundStatusTag: React.FC<{ value?: number }> = ({ value }) => {
|
||||||
|
const label = findLabel(REFUND_STATUS_OPTIONS, value);
|
||||||
|
const color = findColor(REFUND_STATUS_OPTIONS, value);
|
||||||
|
return <Tag color={color}>{label}</Tag>;
|
||||||
|
};
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import type { ProColumns } from '@ant-design/pro-components';
|
||||||
|
import { CtripDistOrderStatusTag, ConsumeStatusTag, RefundStatusTag } from './Tags';
|
||||||
|
|
||||||
|
export interface CtripDistOrderItem {
|
||||||
|
id: number;
|
||||||
|
tenantId?: string;
|
||||||
|
orderNo?: string;
|
||||||
|
ctripOrderId?: number;
|
||||||
|
ctripProductId?: number;
|
||||||
|
ctripPackageId?: number;
|
||||||
|
ctripResourceId?: number;
|
||||||
|
distributorOrderId?: string;
|
||||||
|
orderAmount?: number | string;
|
||||||
|
currency?: string;
|
||||||
|
ctripOrderStatus?: string;
|
||||||
|
consumeStatus?: number;
|
||||||
|
consumeTime?: string;
|
||||||
|
refundStatus?: number;
|
||||||
|
refundTime?: string;
|
||||||
|
refundAmount?: number | string;
|
||||||
|
errorMsg?: string;
|
||||||
|
retryCount?: number;
|
||||||
|
remark?: string;
|
||||||
|
createTime?: string;
|
||||||
|
updateTime?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatAmount = (amount: any): string => {
|
||||||
|
if (amount === undefined || amount === null || amount === '') return '-';
|
||||||
|
const num = parseFloat(String(amount));
|
||||||
|
return isNaN(num) ? '-' : num.toFixed(2);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const buildCtripDistOrderColumns = (): ProColumns<CtripDistOrderItem>[] => [
|
||||||
|
{ dataIndex: 'index', valueType: 'indexBorder', width: 56 },
|
||||||
|
{ title: 'ID', dataIndex: 'id', width: 80 },
|
||||||
|
{ title: '本地订单号', dataIndex: 'orderNo', width: 200, copyable: true, ellipsis: true },
|
||||||
|
{ title: '分销商订单号', dataIndex: 'distributorOrderId', width: 200, copyable: true, ellipsis: true },
|
||||||
|
{ title: '携程订单ID', dataIndex: 'ctripOrderId', width: 160, copyable: true, ellipsis: true },
|
||||||
|
{ title: '携程产品ID', dataIndex: 'ctripProductId', width: 140 },
|
||||||
|
{
|
||||||
|
title: '订单金额',
|
||||||
|
dataIndex: 'orderAmount',
|
||||||
|
width: 120,
|
||||||
|
render: (v, record) => <span>{record.currency || 'CNY'} {formatAmount(v)}</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '携程订单状态',
|
||||||
|
dataIndex: 'ctripOrderStatus',
|
||||||
|
width: 120,
|
||||||
|
render: (v) => <CtripDistOrderStatusTag value={v as string} />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '核销状态',
|
||||||
|
dataIndex: 'consumeStatus',
|
||||||
|
width: 100,
|
||||||
|
render: (v) => <ConsumeStatusTag value={v as number} />,
|
||||||
|
},
|
||||||
|
{ title: '核销时间', dataIndex: 'consumeTime', width: 180, valueType: 'dateTime' },
|
||||||
|
{
|
||||||
|
title: '退款状态',
|
||||||
|
dataIndex: 'refundStatus',
|
||||||
|
width: 100,
|
||||||
|
render: (v) => <RefundStatusTag value={v as number} />,
|
||||||
|
},
|
||||||
|
{ title: '退款时间', dataIndex: 'refundTime', width: 180, valueType: 'dateTime' },
|
||||||
|
{
|
||||||
|
title: '退款金额',
|
||||||
|
dataIndex: 'refundAmount',
|
||||||
|
width: 120,
|
||||||
|
render: (v, record) => {
|
||||||
|
if (v === undefined || v === null || v === '') return '-';
|
||||||
|
return <span>{record.currency || 'CNY'} {formatAmount(v)}</span>;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ title: '租户ID', dataIndex: 'tenantId', width: 140, ellipsis: true },
|
||||||
|
{ title: '重试次数', dataIndex: 'retryCount', width: 90 },
|
||||||
|
{ title: '错误信息', dataIndex: 'errorMsg', width: 200, ellipsis: true },
|
||||||
|
{ title: '备注', dataIndex: 'remark', width: 150, ellipsis: true },
|
||||||
|
{ title: '创建时间', dataIndex: 'createTime', width: 180, valueType: 'dateTime' },
|
||||||
|
{ title: '更新时间', dataIndex: 'updateTime', width: 180, valueType: 'dateTime' },
|
||||||
|
];
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
// 携程分销订单 - 携程侧订单状态(ctripOrderStatus 字符串枚举)
|
||||||
|
export const CTRIP_DIST_ORDER_STATUS_OPTIONS: { label: string; value: string; color?: string }[] = [
|
||||||
|
{ label: '创建中', value: 'CREATING', color: 'processing' },
|
||||||
|
{ label: '已确认', value: 'CONFIRMED', color: 'success' },
|
||||||
|
{ label: '创建失败', value: 'CREATE_FAILED', color: 'error' },
|
||||||
|
{ label: '已取消', value: 'CANCELLED', color: 'default' },
|
||||||
|
];
|
||||||
|
|
||||||
|
// 核销状态
|
||||||
|
export const CONSUME_STATUS_OPTIONS: { label: string; value: number; color?: string }[] = [
|
||||||
|
{ label: '未核销', value: 0, color: 'default' },
|
||||||
|
{ label: '已核销', value: 1, color: 'success' },
|
||||||
|
];
|
||||||
|
|
||||||
|
// 退款状态
|
||||||
|
export const REFUND_STATUS_OPTIONS: { label: string; value: number; color?: string }[] = [
|
||||||
|
{ label: '未退款', value: 0, color: 'default' },
|
||||||
|
{ label: '已退款', value: 1, color: 'success' },
|
||||||
|
{ label: '退款失败', value: 2, color: 'error' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const findLabel = <T extends { label: string; value: V }, V>(arr: T[], v?: V) =>
|
||||||
|
arr.find((o) => o.value === v)?.label || '未知';
|
||||||
|
|
||||||
|
export const findColor = <T extends { color?: string; value: V }, V>(arr: T[], v?: V) =>
|
||||||
|
arr.find((o) => o.value === v)?.color;
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user