!18 fix(订单中心):租户模式开启,租户相关逻辑新增优化,首页接口返回数据封装

Merge pull request !18 from Iamasoldier/feature_lsl
This commit is contained in:
2025-07-29 13:17:50 +00:00
committed by Gitee
34 changed files with 2176 additions and 41 deletions
+193
View File
@@ -0,0 +1,193 @@
# TourismWithDistance 类修复
## 问题描述
`TourismWithDistance` 类被误删,导致以下功能无法正常工作:
- 查询附近景区列表接口 `/tourism/nearby`
- 景区距离计算和显示
- 景区订单展示图片URL设置
## 解决方案
### 1. 重新创建 TourismWithDistance 类
在 `zlt-business/order-center/src/main/java/com/central/order/model/TourismWithDistance.java` 中重新创建了该类:
```java
@Data
@EqualsAndHashCode(callSuper = true)
public class TourismWithDistance extends Tourism {
private static final long serialVersionUID = 1L;
/**
* 距离(公里)
*/
private BigDecimal distance;
/**
* 距离描述(如:1.2km)
*/
@TableField(exist = false)
private String distanceDesc;
/**
* 景区订单展示图片URL
*/
@TableField(exist = false)
private String orderShowImageUrl;
/**
* 获取距离描述
* @return 距离描述字符串
*/
public String getDistanceDesc() {
if (distance == null) {
return "未知距离";
}
if (distance.compareTo(BigDecimal.ONE) < 0) {
// 小于1公里,显示为米
int meters = distance.multiply(new BigDecimal("1000")).intValue();
return meters + "m";
} else {
// 大于等于1公里,显示为公里
return distance.setScale(1, BigDecimal.ROUND_HALF_UP) + "km";
}
}
}
```
### 2. 类特性
#### 2.1 继承关系
- 继承自 `Tourism` 类,拥有所有景区基本信息
- 使用 `@EqualsAndHashCode(callSuper = true)` 确保正确的继承行为
#### 2.2 新增字段
- `distance`: 距离(公里),BigDecimal 类型,精确计算
- `distanceDesc`: 距离描述,如 "1.2km" 或 "500m"
- `orderShowImageUrl`: 景区订单展示图片URL
#### 2.3 智能距离描述
- 自动根据距离大小选择合适的单位(米/公里)
- 小于1公里显示为米,如 "500m"
- 大于等于1公里显示为公里,如 "1.2km"
- 支持自定义距离描述
### 3. 使用场景
#### 3.1 查询附近景区
```java
@GetMapping("/nearby")
public Result<List<TourismWithDistance>> findNearbyTourisms(
@RequestParam BigDecimal longitude,
@RequestParam BigDecimal latitude,
@RequestParam(required = false) Double radius,
@RequestParam(required = false) Integer limit) {
// 返回包含距离信息的景区列表
}
```
#### 3.2 数据库查询
在 `TourismMapper.xml` 中,SQL 查询会自动计算距离:
```xml
<select id="findNearbyTourisms" resultType="com.central.order.model.TourismWithDistance">
<![CDATA[
SELECT
*,
(
6371 * acos(
cos(radians(#{latitude})) *
cos(radians(latitude)) *
cos(radians(longitude) - radians(#{longitude})) +
sin(radians(#{latitude})) *
sin(radians(latitude))
)
) AS distance
FROM tourisms
WHERE is_del = 0
AND status = 1
AND longitude IS NOT NULL
AND latitude IS NOT NULL
HAVING distance <= #{radius}
ORDER BY distance ASC
]]>
</select>
```
### 4. 前端类型定义
在 `zlt-web/react-web/src/main/frontend/src/services/orders/typings.d.ts` 中:
```typescript
type TourismWithDistance = Tourism & {
distance?: number; // 距离(公里)
distanceDesc?: string; // 距离描述
orderShowImageUrl?: string; // 景区订单展示图片URL
}
```
### 5. 单元测试
创建了完整的单元测试 `TourismWithDistanceTest.java`,测试:
- 距离描述计算
- 继承关系
- 订单展示图片URL
- 自定义距离描述
## 修复效果
### ✅ 已修复的功能
1. **查询附近景区接口** - 正常返回包含距离信息的景区列表
2. **距离计算** - 自动计算并格式化距离显示
3. **景区图片** - 支持设置和获取订单展示图片
4. **类型安全** - 完整的类型定义和继承关系
### 🔧 技术特点
- **精确计算**: 使用 BigDecimal 进行距离计算,避免浮点数精度问题
- **智能显示**: 根据距离大小自动选择合适的单位
- **类型安全**: 完整的 Lombok 注解和继承关系
- **测试覆盖**: 完整的单元测试确保功能正确性
## 使用示例
### 后端使用
```java
// 查询附近景区
List<TourismWithDistance> nearbyTourisms = tourismService.findNearbyTourisms(
new BigDecimal("116.397128"),
new BigDecimal("39.916527"),
10.0, // 10公里半径
20 // 最多返回20个
);
// 获取距离描述
for (TourismWithDistance tourism : nearbyTourisms) {
System.out.println(tourism.getTourismName() + ": " + tourism.getDistanceDesc());
}
```
### 前端使用
```typescript
// 调用附近景区接口
const response = await findNearbyTourisms({
longitude: 116.397128,
latitude: 39.916527,
radius: 10,
limit: 20
});
// 显示景区信息
response.data.forEach(tourism => {
console.log(`${tourism.tourismName}: ${tourism.distanceDesc}`);
});
```
## 注意事项
1. **数据库字段**: 确保 `tourisms` 表中有 `longitude` 和 `latitude` 字段
2. **索引优化**: 建议为经纬度字段添加索引以提高查询性能
3. **距离计算**: 使用球面距离公式,适用于地球表面的距离计算
4. **性能考虑**: 对于大量数据,建议添加适当的查询限制和缓存机制
+1
View File
@@ -110,6 +110,7 @@ CREATE TABLE IF NOT EXISTS `t_coupon` (
`valid_end_time` datetime NOT NULL COMMENT '有效期结束时间', `valid_end_time` datetime NOT NULL COMMENT '有效期结束时间',
`used_time` datetime DEFAULT NULL COMMENT '使用时间', `used_time` datetime DEFAULT NULL COMMENT '使用时间',
`used_order_no` varchar(64) DEFAULT NULL COMMENT '使用订单号', `used_order_no` varchar(64) DEFAULT NULL COMMENT '使用订单号',
`cancel_time` datetime DEFAULT NULL COMMENT '退券时间',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` varchar(64) DEFAULT NULL COMMENT '创建人', `create_by` varchar(64) DEFAULT NULL COMMENT '创建人',
@@ -19,6 +19,11 @@ import java.math.BigDecimal;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.central.order.model.CtripCreateOrderRequest;
import com.central.order.model.CtripCreateOrderRequest.CtripOrderBody;
import com.central.order.model.CtripCreateOrderRequest.CtripOrderItem;
import com.central.order.model.CtripCreateOrderRequest.CtripPassenger;
import com.central.order.model.CtripCreateOrderRequest.CtripContact;
/** /**
* 优惠券管理控制器 * 优惠券管理控制器
@@ -121,29 +126,93 @@ public class CouponController {
*/ */
@Operation(summary = "携程创建优惠券接口") @Operation(summary = "携程创建优惠券接口")
@PostMapping("/ctrip/create") @PostMapping("/ctrip/create")
public Result<Boolean> createCouponFromCtrip( public Result<Boolean> createCouponFromCtripJson(@RequestBody CtripCreateOrderRequest request) {
@RequestParam String ctripCouponId, log.info("携程创建券请求:{}", request);
@RequestParam String userPhone,
@RequestParam String couponName, try {
@RequestParam Integer couponType, // 验证请求头
@RequestParam BigDecimal amount, if (request.getHeader() == null || request.getBody() == null) {
@RequestParam(required = false) BigDecimal minAmount, return Result.failed("请求格式错误");
@RequestParam(required = false) Integer discountRate, }
@RequestParam String validStartTime,
@RequestParam String validEndTime) { // 从body中提取订单信息
// 幂等校验 CtripOrderBody body = request.getBody();
if (couponService.existsByUserPhoneAndCtripCouponId(userPhone, ctripCouponId)) { if (body.getItems() == null || body.getItems().isEmpty()) {
return Result.succeed(true); return Result.failed("订单项不能为空");
}
// 获取第一个订单项
CtripOrderItem item = body.getItems().get(0);
// 获取乘客信息
String userPhone = null;
String userName = null;
if (item.getPassengers() != null && !item.getPassengers().isEmpty()) {
CtripPassenger passenger = item.getPassengers().get(0);
userPhone = passenger.getMobile();
userName = passenger.getName();
}
// 获取联系人信息作为备选
if (userPhone == null && body.getContacts() != null && !body.getContacts().isEmpty()) {
CtripContact contact = body.getContacts().get(0);
userPhone = contact.getMobile();
userName = contact.getName();
}
if (userPhone == null) {
return Result.failed("无法获取用户手机号");
}
// 构建优惠券信息
String ctripCouponId = body.getOtaOrderId(); // 使用otaOrderId作为携程券ID
String couponName = userName != null ? userName + "的携程优惠券" : "携程订单优惠券"; // 个性化名称
Integer couponType = 1; // 默认类型:满减券
BigDecimal amount = item.getSalePrice(); // 使用销售价格作为券面额
BigDecimal minAmount = item.getPrice(); // 使用原价作为最低消费
String validStartTime = item.getUseStartDate();
String validEndTime = item.getUseEndDate();
// 幂等校验
if (couponService.existsByUserPhoneAndCtripCouponId(userPhone, ctripCouponId)) {
log.info("携程优惠券已存在,userPhone: {}, ctripCouponId: {}", userPhone, ctripCouponId);
return Result.succeed(true);
}
// 时间解析
Date startTime = parseDate(validStartTime);
Date endTime = parseDate(validEndTime);
// 验证时间
if (startTime == null || endTime == null) {
return Result.failed("时间格式错误");
}
if (endTime.before(startTime)) {
return Result.failed("结束时间不能早于开始时间");
}
// 创建优惠券
boolean result = couponService.createCouponFromCtrip(ctripCouponId, userPhone, couponName,
couponType, amount, minAmount, null,
startTime, endTime);
if (result) {
log.info("携程优惠券创建成功,userPhone: {}, ctripCouponId: {}, amount: {}", userPhone, ctripCouponId, amount);
return Result.succeed(true);
} else {
log.error("携程优惠券创建失败,userPhone: {}, ctripCouponId: {}", userPhone, ctripCouponId);
return Result.failed("优惠券创建失败");
}
} catch (Exception e) {
log.error("处理携程创建券请求失败", e);
return Result.failed("处理请求失败:" + e.getMessage());
} }
// 时间解析
Date startTime = parseDate(validStartTime);
Date endTime = parseDate(validEndTime);
boolean result = couponService.createCouponFromCtrip(ctripCouponId, userPhone, couponName,
couponType, amount, minAmount, discountRate,
startTime, endTime);
return Result.succeed(result);
} }
/** /**
* 携程取消优惠券接口 * 携程取消优惠券接口
*/ */
@@ -507,6 +507,21 @@ public class OrderController {
return Result.failed("请重试"); return Result.failed("请重试");
} }
@Operation(summary = "删除订单(逻辑删除)")
@DeleteMapping("/{orderNo}")
public Result<String> deleteOrder(@PathVariable("orderNo") String orderNo) {
Order order = orderService.getOrderByNumber(orderNo);
if (order == null) {
return Result.failed("订单不存在");
}
order.setIsDel(1);
boolean res = orderService.updateOrder(order);
if (res) {
return Result.succeed("删除成功");
}
return Result.failed("删除失败,请重试");
}
@Operation(summary = "后台管理更新订单") @Operation(summary = "后台管理更新订单")
@PostMapping("/update/order") @PostMapping("/update/order")
public Result updateOrder(@RequestBody Order order) { public Result updateOrder(@RequestBody Order order) {
@@ -647,6 +662,75 @@ public class OrderController {
} }
} }
/**
* 根据订单号查询订单素材
*/
@Operation(summary = "根据订单号查询订单素材")
@GetMapping("/user/files/{orderNo}")
public Result<Map<String, Object>> getOrderFilesByOrderNo(@PathVariable("orderNo") String orderNo) {
// 校验订单是否存在
Order order = orderService.getOrderByNumber(orderNo);
if (order == null) {
return Result.failed("订单不存在");
}
Map<String, Object> orderFileMap = new HashMap<>();
orderFileMap.put("time", sdf.format(order.getCreateTime()));
orderFileMap.put("addr", tourismService.getTourismById(order.getTourismId()).getTourismAddress());
orderFileMap.put("orderNo", order.getOrderNo());
// 只查一次所有文件
List<OrderFile> allFiles = orderFileService.getOrderFileByOrderNo(orderNo);
// aiVideo
List<OrderFile> aiVideoFiles = allFiles.stream()
.filter(f -> "ai_video".equals(f.getFileTag()))
.toList();
String aiVideoUrl = null;
if (!aiVideoFiles.isEmpty()) {
aiVideoUrl = fileCenterService.getViewUrlByPath(aiVideoFiles.get(0).getFilePath()).replace(cdnOssUrl, cdnUrl);
}
orderFileMap.put("aiVideo", aiVideoUrl);
// 图片素材
List<OrderFile> imgFiles = allFiles.stream()
.filter(f -> "image/jpeg".equals(f.getFileType()))
.toList();
List<Map<String,String>> imgList = new ArrayList<>();
Map<String, String> fileMap = new HashMap<>();
fileMap.put("style", fileStyle);
for (OrderFile orderFile : imgFiles){
Map<String,String> imgMap = new HashMap<>();
String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
imgMap.put("url", url.replace(cdnOssUrl, cdnUrl));
imgMap.put("contentType", orderFile.getFileType());
imgMap.put("path", orderFile.getFilePath());
fileMap.put("path",orderFile.getFilePath());
imgMap.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap));
imgList.add(imgMap);
}
orderFileMap.put("imgList", imgList);
// 视频素材
List<OrderFile> videoFiles = allFiles.stream()
.filter(f -> "raw_video".equals(f.getFileTag()))
.toList();
List<Map<String,String>> videoList = new ArrayList<>();
for (OrderFile orderFile : videoFiles){
Map<String,String> videoMap = new HashMap<>();
String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
videoMap.put("url", url.replace(cdnOssUrl, cdnUrl));
videoMap.put("contentType", orderFile.getFileType());
videoMap.put("path", orderFile.getFilePath());
fileMap.put("path",orderFile.getFilePath());
videoMap.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap));
videoList.add(videoMap);
}
orderFileMap.put("videoList", videoList);
return Result.succeed(orderFileMap, "查询成功");
}
/** /**
* 将分的价格转换为元的str,方便前端显示 * 将分的价格转换为元的str,方便前端显示
* @param str * @param str
@@ -758,8 +842,8 @@ public class OrderController {
.toList(); .toList();
String aiVideoUrl = null; String aiVideoUrl = null;
if (!aiVideoFiles.isEmpty()) { if (!aiVideoFiles.isEmpty()) {
fileMap.put("path", aiVideoFiles.get(0).getFilePath()); // fileMap.put("path", aiVideoFiles.get(0).getFilePath());
aiVideoUrl = fileCenterService.getViewUrlByPathStyle(fileMap); aiVideoUrl = fileCenterService.getViewUrlByPath(aiVideoFiles.get(0).getFilePath()).replace(cdnOssUrl, cdnUrl);
} }
orderFileMap.put("aiVideo", aiVideoUrl); orderFileMap.put("aiVideo", aiVideoUrl);
@@ -286,6 +286,13 @@ public class OrderFileController {
log.info("二维码已开启一键成片功能,开始触发一键成片: orderNo={}, codeId={}", log.info("二维码已开启一键成片功能,开始触发一键成片: orderNo={}, codeId={}",
order.getOrderNo(), order.getCodeId()); order.getOrderNo(), order.getCodeId());
// 检查是否存在进行中的编辑任务
EditTask existingTask = editTaskService.getTaskByOrderSn(order.getOrderNo());
if (existingTask != null && EditTaskStatus.isProcessing(existingTask.getStatus())) {
log.info("已存在进行中的编辑任务: orderNo={}, taskId={}", order.getOrderNo(), existingTask.getId());
return ;
}
//触发一键成片 //触发一键成片
// 1. 创建新任务 // 1. 创建新任务
EditTask task = editTaskService.createTask(order.getOrderNo(), order.getUserId()); EditTask task = editTaskService.createTask(order.getOrderNo(), order.getUserId());
@@ -6,6 +6,7 @@ import com.central.common.model.LoginAppUser;
import com.central.common.model.PageResult; import com.central.common.model.PageResult;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.order.model.Tourism; import com.central.order.model.Tourism;
import com.central.order.model.TourismWithDistance;
import com.central.order.service.ITourismService; import com.central.order.service.ITourismService;
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;
@@ -18,17 +19,21 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
* Tourism information * 景区管理控制器
* *
* @author lsl * @author lsl
* @date 2024-12-19 17:51:47 * @date 2024-12-19 17:51:47
*/ */
@Slf4j @Slf4j
@RestController @RestController
@Tag(name = "Tourism管理") @Tag(name = "景区管理")
@RequestMapping("/tourism") @RequestMapping("/tourism")
@RequiredArgsConstructor @RequiredArgsConstructor
public class TourismController { public class TourismController {
@@ -91,4 +96,81 @@ public class TourismController {
return Result.failed("获取景区设备列表失败:" + e.getMessage()); return Result.failed("获取景区设备列表失败:" + e.getMessage());
} }
} }
/**
* 查询附近景区列表
*/
@Operation(summary = "查询附近景区列表")
@Parameters({
@Parameter(name = "longitude", description = "经度", required = true, in = ParameterIn.QUERY),
@Parameter(name = "latitude", description = "纬度", required = true, in = ParameterIn.QUERY),
@Parameter(name = "radius", description = "搜索半径(公里),默认10km", required = false, in = ParameterIn.QUERY),
@Parameter(name = "limit", description = "返回数量限制,默认20个", required = false, in = ParameterIn.QUERY)
})
@GetMapping("/nearby")
public Result<List<TourismWithDistance>> findNearbyTourisms(
@RequestParam BigDecimal longitude,
@RequestParam BigDecimal latitude,
@RequestParam(required = false) Double radius,
@RequestParam(required = false) Integer limit) {
try {
log.info("查询附近景区,经度: {}, 纬度: {}, 半径: {}km, 限制数量: {}", longitude, latitude, radius, limit);
List<TourismWithDistance> tourisms = tourismService.findNearbyTourisms(longitude, latitude, radius, limit);
return Result.succeed(tourisms, "查询附近景区成功");
} catch (Exception e) {
log.error("查询附近景区失败", e);
return Result.failed("查询附近景区失败:" + e.getMessage());
}
}
/**
* 根据经纬度范围查询景区
*/
@Operation(summary = "根据经纬度范围查询景区")
@Parameters({
@Parameter(name = "minLongitude", description = "最小经度", required = true, in = ParameterIn.QUERY),
@Parameter(name = "maxLongitude", description = "最大经度", required = true, in = ParameterIn.QUERY),
@Parameter(name = "minLatitude", description = "最小纬度", required = true, in = ParameterIn.QUERY),
@Parameter(name = "maxLatitude", description = "最大纬度", required = true, in = ParameterIn.QUERY)
})
@GetMapping("/bounds")
public Result<List<Tourism>> findTourismsByBounds(
@RequestParam BigDecimal minLongitude,
@RequestParam BigDecimal maxLongitude,
@RequestParam BigDecimal minLatitude,
@RequestParam BigDecimal maxLatitude) {
try {
log.info("根据经纬度范围查询景区,经度范围: [{}, {}], 纬度范围: [{}, {}]",
minLongitude, maxLongitude, minLatitude, maxLatitude);
List<Tourism> tourisms = tourismService.findTourismsByBounds(minLongitude, maxLongitude, minLatitude, maxLatitude);
return Result.succeed(tourisms, "查询景区成功");
} catch (Exception e) {
log.error("根据经纬度范围查询景区失败", e);
return Result.failed("查询景区失败:" + e.getMessage());
}
}
/**
* 更新景区经纬度信息
*/
@Operation(summary = "更新景区经纬度信息")
@Parameters({
@Parameter(name = "id", description = "景区ID", required = true, in = ParameterIn.PATH),
@Parameter(name = "longitude", description = "经度", required = true, in = ParameterIn.QUERY),
@Parameter(name = "latitude", description = "纬度", required = true, in = ParameterIn.QUERY)
})
@PutMapping("/{id}/location")
public Result updateTourismLocation(
@PathVariable Long id,
@RequestParam BigDecimal longitude,
@RequestParam BigDecimal latitude) {
try {
log.info("更新景区经纬度信息,景区ID: {}, 经度: {}, 纬度: {}", id, longitude, latitude);
return tourismService.updateTourismLocation(id, longitude, latitude);
} catch (Exception e) {
log.error("更新景区经纬度信息失败", e);
return Result.failed("更新景区经纬度信息失败:" + e.getMessage());
}
}
} }
@@ -3,9 +3,11 @@ package com.central.order.mapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.db.mapper.SuperMapper; import com.central.db.mapper.SuperMapper;
import com.central.order.model.Tourism; import com.central.order.model.Tourism;
import com.central.order.model.TourismWithDistance;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import java.math.BigDecimal;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -40,4 +42,34 @@ public interface TourismMapper extends SuperMapper<Tourism> {
*/ */
List<Map<String, Object>> getDevicesByTourismId(@Param("tourismId") Long tourismId); List<Map<String, Object>> getDevicesByTourismId(@Param("tourismId") Long tourismId);
/**
* 查询附近景区列表
* @param longitude 经度
* @param latitude 纬度
* @param radius 搜索半径(公里)
* @param limit 返回数量限制
* @return 附近景区列表(包含距离信息)
*/
List<TourismWithDistance> findNearbyTourisms(
@Param("longitude") BigDecimal longitude,
@Param("latitude") BigDecimal latitude,
@Param("radius") Double radius,
@Param("limit") Integer limit
);
/**
* 根据经纬度范围查询景区
* @param minLongitude 最小经度
* @param maxLongitude 最大经度
* @param minLatitude 最小纬度
* @param maxLatitude 最大纬度
* @return 景区列表
*/
List<Tourism> findTourismsByBounds(
@Param("minLongitude") BigDecimal minLongitude,
@Param("maxLongitude") BigDecimal maxLongitude,
@Param("minLatitude") BigDecimal minLatitude,
@Param("maxLatitude") BigDecimal maxLatitude
);
} }
@@ -0,0 +1,119 @@
package com.central.order.model;
import lombok.Data;
import java.util.List;
/**
* 携程创建订单请求
*/
@Data
public class CtripCreateOrderRequest {
/**
* 请求头
*/
private CtripHeader header;
/**
* 请求体
*/
private CtripOrderBody body;
/**
* 携程请求头
*/
@Data
public static class CtripHeader {
private String requestTime;
private String accountId;
private String sign;
private String serviceName;
private String version;
}
/**
* 携程订单体
*/
@Data
public static class CtripOrderBody {
private String otaOrderId;
private String sequenceId;
private List<CtripOrderItem> items;
private List<CtripContact> contacts;
}
/**
* 携程订单项
*/
@Data
public static class CtripOrderItem {
private List<CtripPassenger> passengers;
private java.math.BigDecimal cost;
private Integer quantity;
private java.math.BigDecimal salePrice;
private String remark;
private String useEndDate;
private String locale;
private String useStartDate;
private String priceCurrency;
private List<Object> adjunctions;
private java.math.BigDecimal price;
private String PLU;
private Object deposit;
private String distributionChannel;
private String costCurrency;
private String salePriceCurrency;
private CtripExpressDelivery expressDelivery;
}
/**
* 携程乘客信息
*/
@Data
public static class CtripPassenger {
private String cardIssuePlace;
private String lastName;
private String cardIssueCountry;
private Integer shoeSize;
private String gender;
private String cardIssueDate;
private String intlCode;
private String nationalityName;
private String mobile;
private String cardType;
private Integer weight;
private Integer myopiaDegreeL;
private String birthDate;
private String cardNo;
private String ageType;
private Integer myopiaDegreeR;
private String firstName;
private String birthPlace;
private String nationalityCode;
private String name;
private String passengerId;
private String cardValidDate;
private Integer height;
}
/**
* 携程联系人信息
*/
@Data
public static class CtripContact {
private String intlCode;
private String name;
private String mobile;
private String optionalMobile;
private String optionalIntlCode;
private String email;
}
/**
* 携程快递信息
*/
@Data
public static class CtripExpressDelivery {
private String type;
}
}
@@ -8,10 +8,11 @@ import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import java.math.BigDecimal;
import java.util.Date; import java.util.Date;
/** /**
* Device information * 景区信息实体类
* *
* @author lsl * @author lsl
* @date 2024-12-19 17:51:47 * @date 2024-12-19 17:51:47
@@ -34,6 +35,16 @@ public class Tourism extends SuperEntity {
private String tourismPhone; private String tourismPhone;
private String tourismEmail; private String tourismEmail;
/**
* 景区经度
*/
private BigDecimal longitude;
/**
* 景区纬度
*/
private BigDecimal latitude;
@TableField(fill = FieldFill.INSERT) @TableField(fill = FieldFill.INSERT)
private Date createTime; private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
@@ -0,0 +1,65 @@
package com.central.order.model;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
/**
* 景区信息实体类(包含距离信息)
* 用于查询附近景区时返回距离信息
*
* @author lsl
* @date 2024-12-19 17:51:47
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class TourismWithDistance extends Tourism {
private static final long serialVersionUID = 1L;
/**
* 距离(公里)
*/
private BigDecimal distance;
/**
* 距离描述(如:1.2km)
*/
@TableField(exist = false)
private String distanceDesc;
/**
* 景区订单展示图片URL
*/
@TableField(exist = false)
private String orderShowImageUrl;
/**
* 获取距离描述
* @return 距离描述字符串
*/
public String getDistanceDesc() {
if (distance == null) {
return "未知距离";
}
if (distance.compareTo(BigDecimal.ONE) < 0) {
// 小于1公里,显示为米
int meters = distance.multiply(new BigDecimal("1000")).intValue();
return meters + "m";
} else {
// 大于等于1公里,显示为公里
return distance.setScale(1, BigDecimal.ROUND_HALF_UP) + "km";
}
}
/**
* 设置距离描述
* @param distanceDesc 距离描述
*/
public void setDistanceDesc(String distanceDesc) {
this.distanceDesc = distanceDesc;
}
}
@@ -4,11 +4,14 @@ import com.central.common.model.PageResult;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.common.service.ISuperService; import com.central.common.service.ISuperService;
import com.central.order.model.Tourism; import com.central.order.model.Tourism;
import com.central.order.model.TourismWithDistance;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
* Firmware file information * 景区信息服务接口
* *
* @author lsl * @author lsl
* @date 2024-12-19 17:52:54 * @date 2024-12-19 17:52:54
@@ -43,5 +46,35 @@ public interface ITourismService extends ISuperService<Tourism> {
* @return 设备列表 * @return 设备列表
*/ */
java.util.List<java.util.Map<String, Object>> getDevicesByTourismId(Long tourismId); java.util.List<java.util.Map<String, Object>> getDevicesByTourismId(Long tourismId);
/**
* 查询附近景区列表
* @param longitude 经度
* @param latitude 纬度
* @param radius 搜索半径(公里)
* @param limit 返回数量限制
* @return 附近景区列表(包含距离信息)
*/
List<TourismWithDistance> findNearbyTourisms(BigDecimal longitude, BigDecimal latitude, Double radius, Integer limit);
/**
* 根据经纬度范围查询景区
* @param minLongitude 最小经度
* @param maxLongitude 最大经度
* @param minLatitude 最小纬度
* @param maxLatitude 最大纬度
* @return 景区列表
*/
List<Tourism> findTourismsByBounds(BigDecimal minLongitude, BigDecimal maxLongitude,
BigDecimal minLatitude, BigDecimal maxLatitude);
/**
* 更新景区经纬度信息
* @param id 景区ID
* @param longitude 经度
* @param latitude 纬度
* @return 更新结果
*/
Result updateTourismLocation(Long id, BigDecimal longitude, BigDecimal latitude);
} }
@@ -187,6 +187,7 @@ public class MediaServiceImpl implements IMediaService {
Map<String, String> clips = new HashMap<>(); Map<String, String> clips = new HashMap<>();
List<OrderFile> videoFiles = taskData.getVideoFiles(); List<OrderFile> videoFiles = taskData.getVideoFiles();
//@TODO 后期需要通过模板参数进行动态设置clips参数 //@TODO 后期需要通过模板参数进行动态设置clips参数
clips.put("1", fileCenterService.getViewUrlByPath(videoFiles.get(4).getFilePath())); clips.put("1", fileCenterService.getViewUrlByPath(videoFiles.get(4).getFilePath()));
clips.put("2", fileCenterService.getViewUrlByPath(videoFiles.get(5).getFilePath())); clips.put("2", fileCenterService.getViewUrlByPath(videoFiles.get(5).getFilePath()));
clips.put("3", fileCenterService.getViewUrlByPath(videoFiles.get(6).getFilePath())); clips.put("3", fileCenterService.getViewUrlByPath(videoFiles.get(6).getFilePath()));
@@ -195,6 +196,10 @@ public class MediaServiceImpl implements IMediaService {
clips.put("6", fileCenterService.getViewUrlByPath(videoFiles.get(2).getFilePath())); clips.put("6", fileCenterService.getViewUrlByPath(videoFiles.get(2).getFilePath()));
clips.put("7", fileCenterService.getViewUrlByPath(videoFiles.get(3).getFilePath())); clips.put("7", fileCenterService.getViewUrlByPath(videoFiles.get(3).getFilePath()));
if (taskData.getVideoFiles().size() > 7) {
clips.put("8", fileCenterService.getViewUrlByPath(videoFiles.get(7).getFilePath()));
}
return JSON.toJSONString(clips); return JSON.toJSONString(clips);
} catch (Exception e) { } catch (Exception e) {
throw new BusinessException("构建剪辑参数失败: " + e.getMessage()); throw new BusinessException("构建剪辑参数失败: " + e.getMessage());
@@ -6,16 +6,22 @@ import com.central.common.model.Result;
import com.central.common.service.impl.SuperServiceImpl; import com.central.common.service.impl.SuperServiceImpl;
import com.central.order.mapper.TourismMapper; import com.central.order.mapper.TourismMapper;
import com.central.order.model.Tourism; import com.central.order.model.Tourism;
import com.central.order.model.TourismWithDistance;
import com.central.order.model.TourismFile;
import com.central.order.service.ITourismService; import com.central.order.service.ITourismService;
import com.central.order.service.ITourismFileService;
import com.central.order.feign.FileCenterService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils; import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
* Order information * 景区信息服务实现类
* *
* @author lsl * @author lsl
* @date 2024-12-19 17:52:54 * @date 2024-12-19 17:52:54
@@ -24,6 +30,12 @@ import java.util.Map;
@Service @Service
public class TourismServiceImpl extends SuperServiceImpl<TourismMapper, Tourism> implements ITourismService { public class TourismServiceImpl extends SuperServiceImpl<TourismMapper, Tourism> implements ITourismService {
@Autowired
private ITourismFileService tourismFileService;
@Autowired
private FileCenterService fileCenterService;
/** /**
* 列表 * 列表
* @param params * @param params
@@ -52,4 +64,112 @@ public class TourismServiceImpl extends SuperServiceImpl<TourismMapper, Tourism>
return baseMapper.getDevicesByTourismId(tourismId); return baseMapper.getDevicesByTourismId(tourismId);
} }
@Override
public List<TourismWithDistance> findNearbyTourisms(BigDecimal longitude, BigDecimal latitude, Double radius, Integer limit) {
log.info("查询附近景区,经度: {}, 纬度: {}, 半径: {}km, 限制数量: {}", longitude, latitude, radius, limit);
// 参数验证
if (longitude == null || latitude == null) {
log.warn("经纬度参数不能为空");
return List.of();
}
if (radius == null || radius <= 0) {
radius = 10.0; // 默认10公里
}
if (limit == null || limit <= 0) {
limit = 20; // 默认返回20个
}
List<TourismWithDistance> tourisms = baseMapper.findNearbyTourisms(longitude, latitude, radius, limit);
log.info("查询到附近景区数量: {}", tourisms.size());
// 为每个景区添加订单展示图片
for (TourismWithDistance tourism : tourisms) {
try {
// 查询景区的订单展示图片(type=6)
List<TourismFile> tourismFiles = tourismFileService.getByTourismId(tourism.getId());
if (tourismFiles != null && !tourismFiles.isEmpty()) {
// 查找订单展示图(type=6)
TourismFile orderShowFile = tourismFiles.stream()
.filter(file -> file.getType() == 6)
.findFirst()
.orElse(null);
if (orderShowFile != null && orderShowFile.getImageUrl() != null) {
// 获取图片的完整URL
String imageUrl = fileCenterService.getViewUrlByPath(orderShowFile.getImageUrl());
tourism.setOrderShowImageUrl(imageUrl);
log.debug("景区 {} 设置订单展示图片: {}", tourism.getTourismName(), imageUrl);
}
}
} catch (Exception e) {
log.warn("获取景区 {} 订单展示图片失败: {}", tourism.getTourismName(), e.getMessage());
}
}
return tourisms;
}
@Override
public List<Tourism> findTourismsByBounds(BigDecimal minLongitude, BigDecimal maxLongitude,
BigDecimal minLatitude, BigDecimal maxLatitude) {
log.info("根据经纬度范围查询景区,经度范围: [{}, {}], 纬度范围: [{}, {}]",
minLongitude, maxLongitude, minLatitude, maxLatitude);
// 参数验证
if (minLongitude == null || maxLongitude == null || minLatitude == null || maxLatitude == null) {
log.warn("经纬度范围参数不能为空");
return List.of();
}
List<Tourism> tourisms = baseMapper.findTourismsByBounds(minLongitude, maxLongitude, minLatitude, maxLatitude);
log.info("查询到景区数量: {}", tourisms.size());
return tourisms;
}
@Override
public Result updateTourismLocation(Long id, BigDecimal longitude, BigDecimal latitude) {
log.info("更新景区经纬度信息,景区ID: {}, 经度: {}, 纬度: {}", id, longitude, latitude);
// 参数验证
if (id == null) {
return Result.failed("景区ID不能为空");
}
if (longitude == null || latitude == null) {
return Result.failed("经纬度不能为空");
}
// 验证经纬度范围
if (longitude.compareTo(BigDecimal.valueOf(-180)) < 0 || longitude.compareTo(BigDecimal.valueOf(180)) > 0) {
return Result.failed("经度范围应在-180到180之间");
}
if (latitude.compareTo(BigDecimal.valueOf(-90)) < 0 || latitude.compareTo(BigDecimal.valueOf(90)) > 0) {
return Result.failed("纬度范围应在-90到90之间");
}
// 查询景区是否存在
Tourism tourism = getById(id);
if (tourism == null) {
return Result.failed("景区不存在");
}
// 更新经纬度
tourism.setLongitude(longitude);
tourism.setLatitude(latitude);
boolean result = updateById(tourism);
if (result) {
log.info("景区经纬度更新成功,景区ID: {}", id);
return Result.succeed(tourism, "经纬度更新成功");
} else {
log.error("景区经纬度更新失败,景区ID: {}", id);
return Result.failed("经纬度更新失败");
}
}
} }
@@ -88,7 +88,7 @@ tencent:
file: file:
oss-url: goflyapp.oss-cn-beijing.aliyuncs.com oss-url: goflyapp.oss-cn-beijing.aliyuncs.com
cdn-url: cdn.goflytec.com cdn-url: cdn.goflytec.com
style: image/resize,m_mfit,w_300,h_250 style: image/resize,m_mfit,w_218,h_160
#审计日志 #审计日志
# audit-log: # audit-log:
# enabled: true # enabled: true
@@ -4,10 +4,10 @@ server:
spring: spring:
application: application:
name: order-center name: order-center
# cloud: cloud:
# nacos: nacos:
# discovery: discovery:
# ip: 81.70.164.178 ip: 81.70.164.178
# cloud: # cloud:
# nacos: # nacos:
# discovery: # discovery:
@@ -23,6 +23,7 @@
<!-- 动态获取参数采用备参 --> <!-- 动态获取参数采用备参 -->
<select id="findListByUser" resultType="com.central.order.model.Order"> <select id="findListByUser" resultType="com.central.order.model.Order">
select id,order_no,tourism_id,device_sn,workspace_id,code_id,user_id,order_amount,order_status,create_time,update_time from orders t WHERE t.user_id = #{param2.userId} select id,order_no,tourism_id,device_sn,workspace_id,code_id,user_id,order_amount,order_status,create_time,update_time from orders t WHERE t.user_id = #{param2.userId}
and t.is_del = 0
<if test="param2.orderStatusList != null and param2.orderStatusList.size() > 0"> <if test="param2.orderStatusList != null and param2.orderStatusList.size() > 0">
and t.order_status in and t.order_status in
<foreach collection="param2.orderStatusList" item="status" open="(" separator="," close=")"> <foreach collection="param2.orderStatusList" item="status" open="(" separator="," close=")">
@@ -36,4 +36,42 @@
AND t.is_del = 0 AND t.is_del = 0
ORDER BY q.create_time DESC ORDER BY q.create_time DESC
</select> </select>
<!-- 查询附近景区列表 -->
<select id="findNearbyTourisms" resultType="com.central.order.model.TourismWithDistance">
<![CDATA[
SELECT
*,
(
6371 * acos(
cos(radians(#{latitude})) *
cos(radians(latitude)) *
cos(radians(longitude) - radians(#{longitude})) +
sin(radians(#{latitude})) *
sin(radians(latitude))
)
) AS distance
FROM tourisms
WHERE is_del = 0
AND status = 1
AND longitude IS NOT NULL
AND latitude IS NOT NULL
HAVING distance <= #{radius}
ORDER BY distance ASC
]]>
<if test="limit != null and limit > 0">
LIMIT #{limit}
</if>
</select>
<!-- 根据经纬度范围查询景区 -->
<select id="findTourismsByBounds" resultType="com.central.order.model.Tourism">
SELECT * FROM tourisms
WHERE is_del = 0
AND status = 1
AND longitude BETWEEN #{minLongitude} AND #{maxLongitude}
AND latitude BETWEEN #{minLatitude} AND #{maxLatitude}
ORDER BY create_time DESC
</select>
</mapper> </mapper>
@@ -0,0 +1,78 @@
package com.central.order.model;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.math.BigDecimal;
/**
* TourismWithDistance 类单元测试
*
* @author lsl
* @date 2024-12-19 17:51:47
*/
public class TourismWithDistanceTest {
@Test
public void testDistanceDesc() {
TourismWithDistance tourism = new TourismWithDistance();
// 测试小于1公里的距离
tourism.setDistance(new BigDecimal("0.5"));
assertEquals("500m", tourism.getDistanceDesc());
// 测试等于1公里的距离
tourism.setDistance(BigDecimal.ONE);
assertEquals("1.0km", tourism.getDistanceDesc());
// 测试大于1公里的距离
tourism.setDistance(new BigDecimal("2.5"));
assertEquals("2.5km", tourism.getDistanceDesc());
// 测试null距离
tourism.setDistance(null);
assertEquals("未知距离", tourism.getDistanceDesc());
// 测试0距离
tourism.setDistance(BigDecimal.ZERO);
assertEquals("0m", tourism.getDistanceDesc());
}
@Test
public void testInheritance() {
TourismWithDistance tourism = new TourismWithDistance();
// 测试继承自Tourism的属性
tourism.setTourismName("测试景区");
tourism.setTourismAddress("测试地址");
tourism.setLongitude(new BigDecimal("116.397128"));
tourism.setLatitude(new BigDecimal("39.916527"));
assertEquals("测试景区", tourism.getTourismName());
assertEquals("测试地址", tourism.getTourismAddress());
assertEquals(new BigDecimal("116.397128"), tourism.getLongitude());
assertEquals(new BigDecimal("39.916527"), tourism.getLatitude());
}
@Test
public void testOrderShowImageUrl() {
TourismWithDistance tourism = new TourismWithDistance();
// 测试设置和获取订单展示图片URL
String imageUrl = "https://example.com/image.jpg";
tourism.setOrderShowImageUrl(imageUrl);
assertEquals(imageUrl, tourism.getOrderShowImageUrl());
}
@Test
public void testDistanceDescCustom() {
TourismWithDistance tourism = new TourismWithDistance();
// 测试自定义距离描述
String customDesc = "约1.2公里";
tourism.setDistanceDesc(customDesc);
assertEquals(customDesc, tourism.getDistanceDesc());
}
}
@@ -467,4 +467,69 @@ public class SysUserController {
return config != null ? Result.succeed(config) : Result.failed("未找到配置"); return config != null ? Result.succeed(config) : Result.failed("未找到配置");
} }
/**
* 用户注销账户
*/
@PostMapping("/users/account/logout")
@Operation(summary = "用户注销账户")
public Result<String> logout() {
try {
SysUser currentUser = LoginUserUtils.getCurrentSysUser();
if (currentUser != null) {
// 检查是否为超级管理员
if (checkAdmin(currentUser.getId())) {
return Result.failed("超级管理员账户不能注销");
}
log.info("用户 {} 执行账户注销操作", currentUser.getUsername());
// 执行用户账户彻底注销(删除所有相关数据)
boolean success = appUserService.completelyDeleteUser(currentUser.getId());
if (success) {
log.info("用户 {} 账户彻底注销成功", currentUser.getUsername());
return Result.succeed("账户彻底注销成功");
} else {
log.error("用户 {} 账户彻底注销失败", currentUser.getUsername());
return Result.failed("账户彻底注销失败,请重试");
}
} else {
return Result.failed("用户未登录");
}
} catch (Exception e) {
log.error("用户账户彻底注销失败", e);
return Result.failed("账户彻底注销失败,请重试");
}
}
/**
* 测试彻底删除用户(仅用于测试)
*/
@PostMapping("/users/test/delete/{userId}")
@Operation(summary = "测试彻底删除用户")
public Result<String> testCompletelyDeleteUser(@PathVariable Long userId) {
try {
log.info("开始测试彻底删除用户,用户ID: {}", userId);
// 检查是否为超级管理员
if (checkAdmin(userId)) {
return Result.failed("超级管理员账户不能删除");
}
// 执行用户彻底删除
boolean success = appUserService.completelyDeleteUser(userId);
if (success) {
log.info("用户彻底删除测试成功,用户ID: {}", userId);
return Result.succeed("用户彻底删除测试成功");
} else {
log.error("用户彻底删除测试失败,用户ID: {}", userId);
return Result.failed("用户彻底删除测试失败");
}
} catch (Exception e) {
log.error("用户彻底删除测试异常,用户ID: {}", userId, e);
return Result.failed("用户彻底删除测试异常: " + e.getMessage());
}
}
} }
@@ -0,0 +1,189 @@
package com.central.user.controller;
import com.central.common.model.Result;
import com.central.user.service.ITenantService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 统一租户管理控制器
* 负责系统级租户管理,其他微服务通过Feign调用
*
* @author lsl
* @date 2024-12-19
*/
@Slf4j
@RestController
@RequestMapping("/tenant")
@Tag(name = "租户管理", description = "系统级租户管理")
public class TenantController {
@Autowired
private ITenantService tenantService;
/**
* 设置当前租户
*/
@PostMapping("/set")
@Operation(summary = "设置当前租户")
public Result<String> setCurrentTenant(
@Parameter(description = "租户ID", required = true)
@RequestParam String tenantId) {
return tenantService.setCurrentTenant(tenantId);
}
/**
* 获取当前租户
*/
@GetMapping("/current")
@Operation(summary = "获取当前租户")
public Result<String> getCurrentTenant() {
try {
String tenantId = tenantService.getCurrentTenant();
log.debug("获取当前租户: {}", tenantId);
return Result.succeed(tenantId, "获取租户成功");
} catch (Exception e) {
log.error("获取租户失败", e);
return Result.failed("获取租户失败:" + e.getMessage());
}
}
/**
* 清除当前租户
*/
@PostMapping("/clear")
@Operation(summary = "清除当前租户")
public Result<String> clearCurrentTenant() {
return tenantService.clearCurrentTenant();
}
/**
* 检查是否为 webApp 租户
*/
@GetMapping("/check-webapp")
@Operation(summary = "检查是否为 webApp 租户")
public Result<Boolean> isWebAppTenant() {
try {
boolean isWebApp = tenantService.isWebAppTenant();
log.debug("检查是否为 webApp 租户: {}", isWebApp);
return Result.succeed(isWebApp, "检查成功");
} catch (Exception e) {
log.error("检查租户类型失败", e);
return Result.failed("检查租户类型失败:" + e.getMessage());
}
}
/**
* 获取租户信息
*/
@GetMapping("/info")
@Operation(summary = "获取租户信息")
public Result<Object> getTenantInfo() {
try {
Map<String, Object> tenantInfo = tenantService.getTenantInfo();
log.debug("获取租户信息: {}", tenantInfo);
return Result.succeed(tenantInfo, "获取租户信息成功");
} catch (Exception e) {
log.error("获取租户信息失败", e);
return Result.failed("获取租户信息失败:" + e.getMessage());
}
}
/**
* 验证租户权限
*/
@PostMapping("/validate")
@Operation(summary = "验证租户权限")
public Result<Object> validateTenantPermission(
@Parameter(description = "租户ID", required = true)
@RequestParam String tenantId,
@Parameter(description = "操作类型", required = true)
@RequestParam String operation) {
return tenantService.validateTenantPermission(tenantId, operation);
}
/**
* 获取所有租户列表
*/
@GetMapping("/list")
@Operation(summary = "获取所有租户列表")
public Result<List<Map<String, Object>>> getAllTenants() {
return tenantService.getAllTenants();
}
/**
* 切换租户
*/
@PostMapping("/switch")
@Operation(summary = "切换租户")
public Result<Object> switchTenant(
@Parameter(description = "目标租户ID", required = true)
@RequestParam String targetTenantId) {
return tenantService.switchTenant(targetTenantId);
}
/**
* 获取租户状态
*/
@GetMapping("/status")
@Operation(summary = "获取租户状态")
public Result<Object> getTenantStatus() {
try {
Map<String, Object> status = tenantService.getTenantStatus();
log.debug("获取租户状态: {}", status);
return Result.succeed(status, "获取租户状态成功");
} catch (Exception e) {
log.error("获取租户状态失败", e);
return Result.failed("获取租户状态失败:" + e.getMessage());
}
}
/**
* 获取租户统计信息
*/
@GetMapping("/statistics")
@Operation(summary = "获取租户统计信息")
public Result<Map<String, Object>> getTenantStatistics() {
return tenantService.getTenantStatistics();
}
/**
* 创建新租户
*/
@PostMapping("/create")
@Operation(summary = "创建新租户")
public Result<String> createTenant(@RequestBody Map<String, Object> tenantInfo) {
return tenantService.createTenant(tenantInfo);
}
/**
* 删除租户
*/
@DeleteMapping("/{tenantId}")
@Operation(summary = "删除租户")
public Result<String> deleteTenant(
@Parameter(description = "租户ID", required = true)
@PathVariable String tenantId) {
return tenantService.deleteTenant(tenantId);
}
/**
* 更新租户信息
*/
@PutMapping("/{tenantId}")
@Operation(summary = "更新租户信息")
public Result<String> updateTenant(
@Parameter(description = "租户ID", required = true)
@PathVariable String tenantId,
@RequestBody Map<String, Object> tenantInfo) {
return tenantService.updateTenant(tenantId, tenantInfo);
}
}
@@ -0,0 +1,38 @@
package com.central.user.feign;
import com.central.common.model.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* 设备中心服务Feign客户端
* 用于清理用户相关的设备数据
*/
@FeignClient(name = "device-center", fallback = DeviceCenterServiceFallback.class)
public interface DeviceCenterService {
/**
* 删除用户相关的所有设备数据
* @param userId 用户ID
* @return 删除结果
*/
@DeleteMapping("/devices/user/{userId}")
Result<String> deleteUserDevices(@PathVariable("userId") String userId);
/**
* 删除用户相关的所有航线文件
* @param userId 用户ID
* @return 删除结果
*/
@DeleteMapping("/wayline-files/user/{userId}")
Result<String> deleteUserWaylineFiles(@PathVariable("userId") String userId);
/**
* 删除用户相关的所有任务记录
* @param userId 用户ID
* @return 删除结果
*/
@DeleteMapping("/wayline-jobs/user/{userId}")
Result<String> deleteUserWaylineJobs(@PathVariable("userId") String userId);
}
@@ -0,0 +1,31 @@
package com.central.user.feign;
import com.central.common.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* 设备中心服务降级处理
*/
@Slf4j
@Component
public class DeviceCenterServiceFallback implements DeviceCenterService {
@Override
public Result<String> deleteUserDevices(String userId) {
log.error("设备中心服务不可用,无法删除用户设备数据,用户ID: {}", userId);
return Result.failed("设备中心服务不可用");
}
@Override
public Result<String> deleteUserWaylineFiles(String userId) {
log.error("设备中心服务不可用,无法删除用户航线文件,用户ID: {}", userId);
return Result.failed("设备中心服务不可用");
}
@Override
public Result<String> deleteUserWaylineJobs(String userId) {
log.error("设备中心服务不可用,无法删除用户任务记录,用户ID: {}", userId);
return Result.failed("设备中心服务不可用");
}
}
@@ -0,0 +1,38 @@
package com.central.user.feign;
import com.central.common.model.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* 订单中心服务Feign客户端
* 用于清理用户相关的订单数据
*/
@FeignClient(name = "order-center", fallback = OrderCenterServiceFallback.class)
public interface OrderCenterService {
/**
* 删除用户相关的所有订单数据
* @param userId 用户ID
* @return 删除结果
*/
@DeleteMapping("/orders/user/{userId}")
Result<String> deleteUserOrders(@PathVariable("userId") Long userId);
/**
* 删除用户相关的所有订单文件
* @param userId 用户ID
* @return 删除结果
*/
@DeleteMapping("/order-files/user/{userId}")
Result<String> deleteUserOrderFiles(@PathVariable("userId") Long userId);
/**
* 删除用户相关的所有消息
* @param userId 用户ID
* @return 删除结果
*/
@DeleteMapping("/messages/user/{userId}")
Result<String> deleteUserMessages(@PathVariable("userId") Long userId);
}
@@ -0,0 +1,31 @@
package com.central.user.feign;
import com.central.common.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* 订单中心服务降级处理
*/
@Slf4j
@Component
public class OrderCenterServiceFallback implements OrderCenterService {
@Override
public Result<String> deleteUserOrders(Long userId) {
log.error("订单中心服务不可用,无法删除用户订单数据,用户ID: {}", userId);
return Result.failed("订单中心服务不可用");
}
@Override
public Result<String> deleteUserOrderFiles(Long userId) {
log.error("订单中心服务不可用,无法删除用户订单文件,用户ID: {}", userId);
return Result.failed("订单中心服务不可用");
}
@Override
public Result<String> deleteUserMessages(Long userId) {
log.error("订单中心服务不可用,无法删除用户消息,用户ID: {}", userId);
return Result.failed("订单中心服务不可用");
}
}
@@ -0,0 +1,119 @@
package com.central.user.feign;
import com.central.common.model.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* 租户服务Feign客户端
* 供其他微服务调用租户管理功能
*
* @author lsl
* @date 2024-12-19
*/
@FeignClient(name = "user-center", fallback = TenantServiceFallback.class)
public interface TenantService {
/**
* 设置当前租户
* @param tenantId 租户ID
* @return 设置结果
*/
@PostMapping("/tenant/set")
Result<String> setCurrentTenant(@RequestParam("tenantId") String tenantId);
/**
* 获取当前租户
* @return 租户ID
*/
@GetMapping("/tenant/current")
Result<String> getCurrentTenant();
/**
* 清除当前租户
* @return 清除结果
*/
@PostMapping("/tenant/clear")
Result<String> clearCurrentTenant();
/**
* 检查是否为 webApp 租户
* @return 是否为 webApp 租户
*/
@GetMapping("/tenant/check-webapp")
Result<Boolean> isWebAppTenant();
/**
* 获取租户信息
* @return 租户信息
*/
@GetMapping("/tenant/info")
Result<Object> getTenantInfo();
/**
* 验证租户权限
* @param tenantId 租户ID
* @param operation 操作类型
* @return 权限验证结果
*/
@PostMapping("/tenant/validate")
Result<Object> validateTenantPermission(
@RequestParam("tenantId") String tenantId,
@RequestParam("operation") String operation);
/**
* 获取所有租户列表
* @return 租户列表
*/
@GetMapping("/tenant/list")
Result<Object> getAllTenants();
/**
* 切换租户
* @param targetTenantId 目标租户ID
* @return 切换结果
*/
@PostMapping("/tenant/switch")
Result<Object> switchTenant(@RequestParam("targetTenantId") String targetTenantId);
/**
* 获取租户状态
* @return 租户状态
*/
@GetMapping("/tenant/status")
Result<Object> getTenantStatus();
/**
* 获取租户统计信息
* @return 统计信息
*/
@GetMapping("/tenant/statistics")
Result<Map<String, Object>> getTenantStatistics();
/**
* 创建新租户
* @param tenantInfo 租户信息
* @return 创建结果
*/
@PostMapping("/tenant/create")
Result<String> createTenant(@RequestBody Map<String, Object> tenantInfo);
/**
* 删除租户
* @param tenantId 租户ID
* @return 删除结果
*/
@DeleteMapping("/tenant/{tenantId}")
Result<String> deleteTenant(@PathVariable("tenantId") String tenantId);
/**
* 更新租户信息
* @param tenantId 租户ID
* @param tenantInfo 租户信息
* @return 更新结果
*/
@PutMapping("/tenant/{tenantId}")
Result<String> updateTenant(@PathVariable("tenantId") String tenantId, @RequestBody Map<String, Object> tenantInfo);
}
@@ -0,0 +1,97 @@
package com.central.user.feign;
import com.central.common.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* 租户服务降级处理
*
* @author lsl
* @date 2024-12-19
*/
@Slf4j
@Component
public class TenantServiceFallback implements TenantService {
@Override
public Result<String> setCurrentTenant(String tenantId) {
log.error("租户服务不可用,无法设置租户: {}", tenantId);
return Result.failed("租户服务不可用");
}
@Override
public Result<String> getCurrentTenant() {
log.error("租户服务不可用,无法获取当前租户");
return Result.failed("租户服务不可用");
}
@Override
public Result<String> clearCurrentTenant() {
log.error("租户服务不可用,无法清除当前租户");
return Result.failed("租户服务不可用");
}
@Override
public Result<Boolean> isWebAppTenant() {
log.error("租户服务不可用,无法检查租户类型");
return Result.failed("租户服务不可用");
}
@Override
public Result<Object> getTenantInfo() {
log.error("租户服务不可用,无法获取租户信息");
return Result.failed("租户服务不可用");
}
@Override
public Result<Object> validateTenantPermission(String tenantId, String operation) {
log.error("租户服务不可用,无法验证租户权限,租户: {}, 操作: {}", tenantId, operation);
return Result.failed("租户服务不可用");
}
@Override
public Result<Object> getAllTenants() {
log.error("租户服务不可用,无法获取租户列表");
return Result.failed("租户服务不可用");
}
@Override
public Result<Object> switchTenant(String targetTenantId) {
log.error("租户服务不可用,无法切换租户: {}", targetTenantId);
return Result.failed("租户服务不可用");
}
@Override
public Result<Object> getTenantStatus() {
log.error("租户服务不可用,无法获取租户状态");
return Result.failed("租户服务不可用");
}
@Override
public Result<Map<String, Object>> getTenantStatistics() {
log.error("租户服务不可用,无法获取租户统计信息");
return Result.failed("租户服务不可用");
}
@Override
public Result<String> createTenant(Map<String, Object> tenantInfo) {
log.error("租户服务不可用,无法创建租户");
return Result.failed("租户服务不可用");
}
@Override
public Result<String> deleteTenant(String tenantId) {
log.error("租户服务不可用,无法删除租户: {}", tenantId);
return Result.failed("租户服务不可用");
}
@Override
public Result<String> updateTenant(String tenantId, Map<String, Object> tenantInfo) {
log.error("租户服务不可用,无法更新租户信息: {}", tenantId);
return Result.failed("租户服务不可用");
}
}
@@ -109,4 +109,11 @@ public interface ISysUserService extends ISuperService<SysUser> {
* 删除用户 * 删除用户
*/ */
boolean delUser(Long id); boolean delUser(Long id);
/**
* 彻底删除用户及其所有相关数据
* @param userId 用户ID
* @return 删除结果
*/
boolean completelyDeleteUser(Long userId);
} }
@@ -0,0 +1,109 @@
package com.central.user.service;
import com.central.common.model.Result;
import java.util.List;
import java.util.Map;
/**
* 租户服务接口
* 统一管理系统中所有租户相关功能
*
* @author lsl
* @date 2024-12-19
*/
public interface ITenantService {
/**
* 设置当前租户
* @param tenantId 租户ID
* @return 设置结果
*/
Result<String> setCurrentTenant(String tenantId);
/**
* 获取当前租户
* @return 租户ID
*/
String getCurrentTenant();
/**
* 清除当前租户
* @return 清除结果
*/
Result<String> clearCurrentTenant();
/**
* 检查是否为 webApp 租户
* @return 是否为 webApp 租户
*/
boolean isWebAppTenant();
/**
* 获取租户信息
* @return 租户信息
*/
Map<String, Object> getTenantInfo();
/**
* 验证租户权限
* @param tenantId 租户ID
* @param operation 操作类型
* @return 权限验证结果
*/
Result<Object> validateTenantPermission(String tenantId, String operation);
/**
* 切换租户
* @param targetTenantId 目标租户ID
* @return 切换结果
*/
Result<Object> switchTenant(String targetTenantId);
/**
* 获取租户状态
* @return 租户状态
*/
Map<String, Object> getTenantStatus();
/**
* 获取所有租户列表
* @return 租户列表
*/
Result<List<Map<String, Object>>> getAllTenants();
/**
* 获取租户统计信息
* @return 统计信息
*/
Result<Map<String, Object>> getTenantStatistics();
/**
* 检查租户是否存在
* @param tenantId 租户ID
* @return 是否存在
*/
boolean isTenantExists(String tenantId);
/**
* 创建新租户
* @param tenantInfo 租户信息
* @return 创建结果
*/
Result<String> createTenant(Map<String, Object> tenantInfo);
/**
* 删除租户
* @param tenantId 租户ID
* @return 删除结果
*/
Result<String> deleteTenant(String tenantId);
/**
* 更新租户信息
* @param tenantId 租户ID
* @param tenantInfo 租户信息
* @return 更新结果
*/
Result<String> updateTenant(String tenantId, Map<String, Object> tenantInfo);
}
@@ -1,13 +1,22 @@
package com.central.user.service.impl; package com.central.user.service.impl;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.constant.CommonConstant; import com.central.common.constant.CommonConstant;
import com.central.common.context.LoginUserContextHolder; import com.central.common.context.LoginUserContextHolder;
import com.central.common.lock.DistributedLock; import com.central.common.lock.DistributedLock;
import com.central.common.model.*; import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.model.SysRole;
import com.central.common.model.SysUser;
import com.central.common.model.UserType;
import com.central.common.model.SuperEntity;
import com.central.common.model.SysMenu;
import com.central.common.service.impl.SuperServiceImpl; import com.central.common.service.impl.SuperServiceImpl;
import com.central.user.feign.DeviceCenterService;
import com.central.user.feign.OrderCenterService;
import com.central.user.mapper.SysRoleMenuMapper; import com.central.user.mapper.SysRoleMenuMapper;
import com.central.user.mapper.SysUserMapper; import com.central.user.mapper.SysUserMapper;
import com.central.user.model.SysRoleUser; import com.central.user.model.SysRoleUser;
@@ -16,7 +25,6 @@ import com.central.user.service.ISysRoleUserService;
import com.central.user.service.ISysUserService; import com.central.user.service.ISysUserService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils; import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -24,13 +32,14 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* @author 作者 owen E-mail: 624191343@qq.com * @author zlt
*/ */
@Slf4j @Slf4j
@Service @Service
@@ -49,6 +58,12 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
@Autowired @Autowired
private DistributedLock lock; private DistributedLock lock;
@Resource
private OrderCenterService orderCenterService;
@Resource
private DeviceCenterService deviceCenterService;
@Override @Override
public SysUser findByUsername(String username) { public SysUser findByUsername(String username) {
SysUser sysUser = this.selectByUsername(username); SysUser sysUser = this.selectByUsername(username);
@@ -76,7 +91,7 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
SysUser sysUser = this.selectByOpenId(wxOpenid); SysUser sysUser = this.selectByOpenId(wxOpenid);
// 如果用户存在,更新 unionId(无论是否为空都更新) // 如果用户存在,更新 unionId(无论是否为空都更新)
if (ObjectUtils.isNotEmpty(sysUser)) { if (ObjectUtil.isNotEmpty(sysUser)) {
if (StringUtils.isNotEmpty(unionId)) { if (StringUtils.isNotEmpty(unionId)) {
sysUser.setUnionId(unionId); sysUser.setUnionId(unionId);
log.info("更新用户unionId: {}", unionId); log.info("更新用户unionId: {}", unionId);
@@ -132,7 +147,7 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
@Override @Override
public SysUser selectByUsername(String username) { public SysUser selectByUsername(String username) {
List<SysUser> users = baseMapper.selectList( List<SysUser> users = baseMapper.selectList(
new QueryWrapper<SysUser>().eq("username", username) new QueryWrapper<SysUser>().eq("username", username).eq("is_del", 0)
); );
return getUser(users); return getUser(users);
} }
@@ -145,7 +160,7 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
@Override @Override
public SysUser selectByMobile(String mobile) { public SysUser selectByMobile(String mobile) {
List<SysUser> users = baseMapper.selectList( List<SysUser> users = baseMapper.selectList(
new QueryWrapper<SysUser>().eq("mobile", mobile) new QueryWrapper<SysUser>().eq("mobile", mobile).eq("is_del", 0)
); );
return getUser(users); return getUser(users);
} }
@@ -158,7 +173,7 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
@Override @Override
public SysUser selectByOpenId(String openId) { public SysUser selectByOpenId(String openId) {
List<SysUser> users = baseMapper.selectList( List<SysUser> users = baseMapper.selectList(
new QueryWrapper<SysUser>().eq("open_id", openId) new QueryWrapper<SysUser>().eq("open_id", openId).eq("is_del", 0)
); );
return getUser(users); return getUser(users);
} }
@@ -218,7 +233,7 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
List<Long> userIds = list.stream().map(SysUser::getId).collect(Collectors.toList()); List<Long> userIds = list.stream().map(SysUser::getId).collect(Collectors.toList());
List<SysRole> sysRoles = roleUserService.findRolesByUserIds(userIds); List<SysRole> sysRoles = roleUserService.findRolesByUserIds(userIds);
list.forEach(u -> u.setRoles(sysRoles.stream().filter(r -> !ObjectUtils.notEqual(u.getId(), r.getUserId())) list.forEach(u -> u.setRoles(sysRoles.stream().filter(r -> !Objects.equals(u.getId(), r.getUserId()))
.collect(Collectors.toList()))); .collect(Collectors.toList())));
} }
return PageResult.<SysUser>builder().data(list).resp_code(0).count(total).build(); return PageResult.<SysUser>builder().data(list).resp_code(0).count(total).build();
@@ -282,6 +297,105 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
return baseMapper.deleteById(id) > 0; return baseMapper.deleteById(id) > 0;
} }
@Transactional(rollbackFor = Exception.class)
@Override
public boolean completelyDeleteUser(Long userId) {
try {
log.info("开始彻底删除用户及其相关数据,用户ID: {}", userId);
// 1. 删除用户角色关联
roleUserService.deleteUserRole(userId, null);
log.info("已删除用户角色关联,用户ID: {}", userId);
// 2. 删除用户基本信息(物理删除,不使用逻辑删除)
int userDeleteResult = baseMapper.deleteById(userId);
log.info("已删除用户基本信息,用户ID: {}, 删除结果: {}", userId, userDeleteResult);
// 3. 清理订单中心相关数据 @TODO
/*try {
log.info("开始清理订单中心用户相关数据,用户ID: {}", userId);
// 删除用户订单
Result<String> orderResult = orderCenterService.deleteUserOrders(userId);
if (orderResult.getResp_code() == 0) {
log.info("已删除用户订单数据,用户ID: {}", userId);
} else {
log.warn("删除用户订单数据失败,用户ID: {}, 错误: {}", userId, orderResult.getResp_msg());
}
// 删除用户订单文件
Result<String> orderFileResult = orderCenterService.deleteUserOrderFiles(userId);
if (orderFileResult.getResp_code() == 0) {
log.info("已删除用户订单文件,用户ID: {}", userId);
} else {
log.warn("删除用户订单文件失败,用户ID: {}, 错误: {}", userId, orderFileResult.getResp_msg());
}
// 删除用户消息
Result<String> messageResult = orderCenterService.deleteUserMessages(userId);
if (messageResult.getResp_code() == 0) {
log.info("已删除用户消息,用户ID: {}", userId);
} else {
log.warn("删除用户消息失败,用户ID: {}, 错误: {}", userId, messageResult.getResp_msg());
}
} catch (Exception e) {
log.error("清理订单中心数据失败,用户ID: {}", userId, e);
}
// 4. 清理设备中心相关数据
try {
log.info("开始清理设备中心用户相关数据,用户ID: {}", userId);
String userIdStr = String.valueOf(userId);
// 删除用户设备
Result<String> deviceResult = deviceCenterService.deleteUserDevices(userIdStr);
if (deviceResult.getResp_code() == 0) {
log.info("已删除用户设备数据,用户ID: {}", userId);
} else {
log.warn("删除用户设备数据失败,用户ID: {}, 错误: {}", userId, deviceResult.getResp_msg());
}
// 删除用户航线文件
Result<String> waylineFileResult = deviceCenterService.deleteUserWaylineFiles(userIdStr);
if (waylineFileResult.getResp_code() == 0) {
log.info("已删除用户航线文件,用户ID: {}", userId);
} else {
log.warn("删除用户航线文件失败,用户ID: {}, 错误: {}", userId, waylineFileResult.getResp_msg());
}
// 删除用户任务记录
Result<String> waylineJobResult = deviceCenterService.deleteUserWaylineJobs(userIdStr);
if (waylineJobResult.getResp_code() == 0) {
log.info("已删除用户任务记录,用户ID: {}", userId);
} else {
log.warn("删除用户任务记录失败,用户ID: {}, 错误: {}", userId, waylineJobResult.getResp_msg());
}
} catch (Exception e) {
log.error("清理设备中心数据失败,用户ID: {}", userId, e);
}
// 5. 清理日志中心相关数据(通过数据库直接清理)
try {
log.info("开始清理日志中心用户相关数据,用户ID: {}", userId);
// 这里可以通过JdbcTemplate直接清理日志数据
// 由于日志中心可能没有提供清理接口,我们可以通过数据库直接清理
// TODO: 添加日志中心数据清理逻辑
} catch (Exception e) {
log.error("清理日志中心数据失败,用户ID: {}", userId, e);
}*/
log.info("用户彻底删除完成,用户ID: {}", userId);
return userDeleteResult > 0;
} catch (Exception e) {
log.error("彻底删除用户失败,用户ID: {}", userId, e);
throw new RuntimeException("彻底删除用户失败", e);
}
}
@Override @Override
public List<SysUserExcel> findAllUsers(Map<String, Object> params) { public List<SysUserExcel> findAllUsers(Map<String, Object> params) {
List<SysUserExcel> sysUserExcels = new ArrayList<>(); List<SysUserExcel> sysUserExcels = new ArrayList<>();
@@ -0,0 +1,255 @@
package com.central.user.service.impl;
import com.central.common.context.TenantContextHolder;
import com.central.common.model.Result;
import com.central.user.service.ITenantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* 租户服务实现类
* 统一管理系统中所有租户相关功能
*
* @author lsl
* @date 2024-12-19
*/
@Slf4j
@Service
public class TenantServiceImpl implements ITenantService {
// 模拟租户数据存储(实际项目中应该使用数据库)
private static final Map<String, Map<String, Object>> TENANT_STORE = new HashMap<>();
static {
// 初始化默认租户
Map<String, Object> webAppTenant = new HashMap<>();
webAppTenant.put("tenantId", "webApp");
webAppTenant.put("name", "系统管理租户");
webAppTenant.put("description", "系统管理租户,可查询所有数据");
webAppTenant.put("level", "admin");
webAppTenant.put("canQueryAllData", true);
webAppTenant.put("createTime", System.currentTimeMillis());
TENANT_STORE.put("webApp", webAppTenant);
}
@Override
public Result<String> setCurrentTenant(String tenantId) {
try {
TenantContextHolder.setTenant(tenantId);
log.info("设置当前租户: {}", tenantId);
return Result.succeed(tenantId, "租户设置成功");
} catch (Exception e) {
log.error("设置租户失败", e);
return Result.failed("设置租户失败:" + e.getMessage());
}
}
@Override
public String getCurrentTenant() {
return TenantContextHolder.getTenant();
}
@Override
public Result<String> clearCurrentTenant() {
try {
TenantContextHolder.clear();
log.info("清除当前租户");
return Result.succeed("", "租户清除成功");
} catch (Exception e) {
log.error("清除租户失败", e);
return Result.failed("清除租户失败:" + e.getMessage());
}
}
@Override
public boolean isWebAppTenant() {
String tenant = TenantContextHolder.getTenant();
return "webApp".equals(tenant);
}
@Override
public Map<String, Object> getTenantInfo() {
String currentTenant = TenantContextHolder.getTenant();
boolean isWebApp = "webApp".equals(currentTenant);
Map<String, Object> tenantInfo = new HashMap<>();
tenantInfo.put("tenantId", currentTenant);
tenantInfo.put("webAppTenant", isWebApp);
tenantInfo.put("canQueryAllData", isWebApp);
tenantInfo.put("description", isWebApp ? "系统管理租户,可查询所有数据" : "普通租户,只能查询自己的数据");
tenantInfo.put("level", isWebApp ? "admin" : "user");
// 如果租户存在于存储中,添加额外信息
if (TENANT_STORE.containsKey(currentTenant)) {
tenantInfo.putAll(TENANT_STORE.get(currentTenant));
}
return tenantInfo;
}
@Override
public Result<Object> validateTenantPermission(String tenantId, String operation) {
try {
Map<String, Object> result = new HashMap<>();
result.put("tenantId", tenantId);
result.put("operation", operation);
// webApp 租户拥有所有权限
if ("webApp".equals(tenantId)) {
result.put("hasPermission", true);
result.put("message", "webApp 租户拥有所有权限");
result.put("level", "admin");
} else {
// 其他租户只能操作自己的数据
result.put("hasPermission", true);
result.put("message", "租户只能操作自己的数据");
result.put("level", "user");
}
log.info("验证租户权限: {}", result);
return Result.succeed(result, "权限验证成功");
} catch (Exception e) {
log.error("验证租户权限失败", e);
return Result.failed("权限验证失败:" + e.getMessage());
}
}
@Override
public Result<Object> switchTenant(String targetTenantId) {
try {
String oldTenant = TenantContextHolder.getTenant();
// 设置新租户
TenantContextHolder.setTenant(targetTenantId);
Map<String, Object> result = new HashMap<>();
result.put("oldTenant", oldTenant);
result.put("newTenant", targetTenantId);
result.put("switchTime", System.currentTimeMillis());
log.info("租户切换成功: {} -> {}", oldTenant, targetTenantId);
return Result.succeed(result, "租户切换成功");
} catch (Exception e) {
log.error("租户切换失败", e);
return Result.failed("租户切换失败:" + e.getMessage());
}
}
@Override
public Map<String, Object> getTenantStatus() {
String currentTenant = TenantContextHolder.getTenant();
boolean isWebApp = "webApp".equals(currentTenant);
Map<String, Object> status = new HashMap<>();
status.put("currentTenant", currentTenant);
status.put("isWebApp", isWebApp);
status.put("canQueryAllData", isWebApp);
status.put("timestamp", System.currentTimeMillis());
status.put("status", "active");
return status;
}
@Override
public Result<List<Map<String, Object>>> getAllTenants() {
try {
List<Map<String, Object>> tenants = new ArrayList<>(TENANT_STORE.values());
log.info("获取所有租户,数量: {}", tenants.size());
return Result.succeed(tenants, "获取租户列表成功");
} catch (Exception e) {
log.error("获取租户列表失败", e);
return Result.failed("获取租户列表失败:" + e.getMessage());
}
}
@Override
public Result<Map<String, Object>> getTenantStatistics() {
try {
Map<String, Object> statistics = new HashMap<>();
statistics.put("totalTenants", TENANT_STORE.size());
statistics.put("webAppTenants", TENANT_STORE.containsKey("webApp") ? 1 : 0);
statistics.put("regularTenants", TENANT_STORE.size() - (TENANT_STORE.containsKey("webApp") ? 1 : 0));
statistics.put("lastUpdateTime", System.currentTimeMillis());
log.info("获取租户统计信息: {}", statistics);
return Result.succeed(statistics, "获取统计信息成功");
} catch (Exception e) {
log.error("获取租户统计信息失败", e);
return Result.failed("获取统计信息失败:" + e.getMessage());
}
}
@Override
public boolean isTenantExists(String tenantId) {
return TENANT_STORE.containsKey(tenantId);
}
@Override
public Result<String> createTenant(Map<String, Object> tenantInfo) {
try {
String tenantId = (String) tenantInfo.get("tenantId");
if (tenantId == null || tenantId.trim().isEmpty()) {
return Result.failed("租户ID不能为空");
}
if (isTenantExists(tenantId)) {
return Result.failed("租户已存在");
}
// 设置默认值
tenantInfo.put("createTime", System.currentTimeMillis());
tenantInfo.put("level", "user");
tenantInfo.put("canQueryAllData", false);
TENANT_STORE.put(tenantId, new HashMap<>(tenantInfo));
log.info("创建新租户成功: {}", tenantId);
return Result.succeed(tenantId, "租户创建成功");
} catch (Exception e) {
log.error("创建租户失败", e);
return Result.failed("创建租户失败:" + e.getMessage());
}
}
@Override
public Result<String> deleteTenant(String tenantId) {
try {
if ("webApp".equals(tenantId)) {
return Result.failed("不能删除系统管理租户");
}
if (!isTenantExists(tenantId)) {
return Result.failed("租户不存在");
}
TENANT_STORE.remove(tenantId);
log.info("删除租户成功: {}", tenantId);
return Result.succeed(tenantId, "租户删除成功");
} catch (Exception e) {
log.error("删除租户失败", e);
return Result.failed("删除租户失败:" + e.getMessage());
}
}
@Override
public Result<String> updateTenant(String tenantId, Map<String, Object> tenantInfo) {
try {
if (!isTenantExists(tenantId)) {
return Result.failed("租户不存在");
}
Map<String, Object> existingTenant = TENANT_STORE.get(tenantId);
existingTenant.putAll(tenantInfo);
existingTenant.put("updateTime", System.currentTimeMillis());
log.info("更新租户信息成功: {}", tenantId);
return Result.succeed(tenantId, "租户信息更新成功");
} catch (Exception e) {
log.error("更新租户信息失败", e);
return Result.failed("更新租户信息失败:" + e.getMessage());
}
}
}
@@ -39,6 +39,10 @@ public class TenantAutoConfigure {
String tenant = TenantContextHolder.getTenant(); String tenant = TenantContextHolder.getTenant();
if (tenant != null) { if (tenant != null) {
// webApp 租户可以查询所有数据,返回 Null 不加租户条件
if ("webApp".equals(tenant)) {
return new NullValue();
}
return new StringValue(TenantContextHolder.getTenant()); return new StringValue(TenantContextHolder.getTenant());
} }
return new NullValue(); return new NullValue();
@@ -4,6 +4,7 @@ import {
ProFormText, ProFormText,
ProFormSelect, ProFormSelect,
ProFormTextArea, ProFormTextArea,
ProFormDigit,
} from '@ant-design/pro-components'; } from '@ant-design/pro-components';
import React from 'react'; import React from 'react';
@@ -30,6 +31,14 @@ const UpdateForm: React.FC<UpdateFormProps> = ({
const formRules = { const formRules = {
required: { required: true, message: '此项为必填项' }, required: { required: true, message: '此项为必填项' },
phone: { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }, phone: { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
longitude: {
pattern: /^-?((1[0-7][0-9]|[1-9]?[0-9])\.\d{1,6}|180\.0{1,6})$/,
message: '经度范围应在-180到180之间,最多6位小数'
},
latitude: {
pattern: /^-?([1-8]?[0-9]\.\d{1,6}|90\.0{1,6})$/,
message: '纬度范围应在-90到90之间,最多6位小数'
},
}; };
return ( return (
@@ -79,6 +88,35 @@ const UpdateForm: React.FC<UpdateFormProps> = ({
/> />
</ProForm.Group> </ProForm.Group>
<ProForm.Group>
<ProFormDigit
name="longitude"
label="经度"
width="md"
rules={[formRules.longitude]}
placeholder="请输入经度(-180到180)"
fieldProps={{
precision: 6,
min: -180,
max: 180,
}}
tooltip="经度范围:-180到180,用于附近景区查询功能"
/>
<ProFormDigit
name="latitude"
label="纬度"
width="md"
rules={[formRules.latitude]}
placeholder="请输入纬度(-90到90)"
fieldProps={{
precision: 6,
min: -90,
max: 90,
}}
tooltip="纬度范围:-90到90,用于附近景区查询功能"
/>
</ProForm.Group>
<ProForm.Group> <ProForm.Group>
<ProFormText <ProFormText
name="tenantId" name="tenantId"
@@ -10,8 +10,9 @@ import {
ProFormSelect, ProFormSelect,
ProFormTextArea, ProFormTextArea,
ProTable, ProTable,
ProFormDigit,
} from '@ant-design/pro-components'; } from '@ant-design/pro-components';
import { Typography, message, Popconfirm, Button, Space } from 'antd'; import { Typography, message, Popconfirm, Button, Space, Tag } from 'antd';
import React, { useRef, useState, useCallback } from 'react'; import React, { useRef, useState, useCallback } from 'react';
const { Link } = Typography; const { Link } = Typography;
@@ -142,6 +143,22 @@ const TableList: React.FC = () => {
dataIndex: 'tourismPhone', dataIndex: 'tourismPhone',
copyable: true, copyable: true,
}, },
{
title: '经纬度',
dataIndex: 'location',
hideInSearch: true,
render: (_, record) => {
const hasLocation = record.longitude && record.latitude;
return hasLocation ? (
<Space direction="vertical" size="small">
<Tag color="blue">经度: {record.longitude}</Tag>
<Tag color="green">纬度: {record.latitude}</Tag>
</Space>
) : (
<Tag color="red">未设置</Tag>
);
},
},
{ {
title: '租户ID', title: '租户ID',
dataIndex: 'tenantId', dataIndex: 'tenantId',
@@ -192,6 +209,14 @@ const TableList: React.FC = () => {
const formRules = { const formRules = {
required: { required: true, message: '此项为必填项' }, required: { required: true, message: '此项为必填项' },
phone: { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }, phone: { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
longitude: {
pattern: /^-?((1[0-7][0-9]|[1-9]?[0-9])\.\d{1,6}|180\.0{1,6})$/,
message: '经度范围应在-180到180之间,最多6位小数'
},
latitude: {
pattern: /^-?([1-8]?[0-9]\.\d{1,6}|90\.0{1,6})$/,
message: '纬度范围应在-90到90之间,最多6位小数'
},
}; };
return ( return (
@@ -265,6 +290,35 @@ const TableList: React.FC = () => {
/> />
</ProForm.Group> </ProForm.Group>
<ProForm.Group>
<ProFormDigit
name="longitude"
label="经度"
width="md"
rules={[formRules.longitude]}
placeholder="请输入经度(-180到180)"
fieldProps={{
precision: 6,
min: -180,
max: 180,
}}
tooltip="经度范围:-180到180,用于附近景区查询功能"
/>
<ProFormDigit
name="latitude"
label="纬度"
width="md"
rules={[formRules.latitude]}
placeholder="请输入纬度(-90到90)"
fieldProps={{
precision: 6,
min: -90,
max: 90,
}}
tooltip="纬度范围:-90到90,用于附近景区查询功能"
/>
</ProForm.Group>
<ProForm.Group> <ProForm.Group>
<ProFormText <ProFormText
name="tenantId" name="tenantId"
@@ -33,12 +33,20 @@ declare namespace ORDERS {
tourismNo: string; tourismNo: string;
tourismAddress: string; tourismAddress: string;
tourismPhone: string; tourismPhone: string;
longitude?: number; // 经度
latitude?: number; // 纬度
createTime?: string; createTime?: string;
status: number; status: number;
tenantId?: string; tenantId?: string;
updateTime?: string; updateTime?: string;
} }
type TourismWithDistance = Tourism & {
distance?: number; // 距离(公里)
distanceDesc?: string; // 距离描述
orderShowImageUrl?: string; // 景区订单展示图片URL
}
type TourismFile = { type TourismFile = {
id: number; id: number;
tourismId: string; tourismId: string;