Please enter the commit message for your changes. Lines starting

with '#' will be ignored, and an empty message aborts the commit.

On branch develop
Your branch is ahead of 'goflyapp/develop' by 2 commits.
  (use "git push" to publish your local commits)

Changes to be committed:
	modified:   README.md
	modified:   pom.xml
	modified:   zlt-business/device-center/pom.xml
	modified:   zlt-business/device-center/src/main/java/com/central/device/controller/AgeDeviceController.java
	modified:   zlt-business/device-center/src/main/java/com/central/device/controller/ApiDeviceController.java
	modified:   zlt-business/device-center/src/main/java/com/central/device/controller/LineFileController.java
	modified:   zlt-business/device-center/src/main/java/com/central/device/feign/OrderCenterService.java
	modified:   zlt-business/device-center/src/main/java/com/central/device/feign/fallback/OrderCenterServiceFallbackFactory.java
	modified:   zlt-business/device-center/src/main/java/com/central/device/listener/DeviceImportListener.java
	modified:   zlt-business/device-center/src/main/java/com/central/device/model/AgeDevice.java
	modified:   zlt-business/device-center/src/main/java/com/central/device/model/LineFile.java
	modified:   zlt-business/device-center/src/main/java/com/central/device/model/excel/AgeDeviceExcel.java
	modified:   zlt-business/device-center/src/main/java/com/central/device/service/IAgeDeviceService.java
	modified:   zlt-business/device-center/src/main/java/com/central/device/service/ILineFileService.java
	modified:   zlt-business/device-center/src/main/java/com/central/device/service/impl/AgeDeviceServiceImpl.java
	modified:   zlt-business/device-center/src/main/java/com/central/device/service/impl/LineFileServiceImpl.java
	modified:   zlt-business/file-center/src/main/java/com/central/file/controller/FileController.java
	modified:   zlt-business/file-center/src/main/java/com/central/file/service/impl/OssService.java
	modified:   zlt-business/file-center/src/main/resources/application.yml
	modified:   zlt-business/order-center/src/main/java/com/central/order/controller/OrderController.java
	modified:   zlt-business/order-center/src/main/java/com/central/order/controller/QrCodeController.java
	modified:   zlt-business/order-center/src/main/java/com/central/order/feign/DeviceCenterService.java
	modified:   zlt-business/order-center/src/main/java/com/central/order/feign/fallback/DeviceCenterServiceFallbackFactory.java
	modified:   zlt-business/order-center/src/main/java/com/central/order/model/Order.java
	modified:   zlt-commons/zlt-common-core/src/main/java/com/central/common/model/FileInfo.java
	modified:   zlt-web/react-web/src/main/frontend/config/config.ts
	modified:   zlt-web/react-web/src/main/frontend/config/routes.ts
	modified:   zlt-web/react-web/src/main/frontend/nginx.conf
	modified:   zlt-web/react-web/src/main/frontend/package.json
	new file:   zlt-web/react-web/src/main/frontend/src/pages/device/Device/components/UpdateForm.tsx
	new file:   zlt-web/react-web/src/main/frontend/src/pages/device/Device/index.tsx
	modified:   zlt-web/react-web/src/main/frontend/src/pages/device/Wayline/components/UpdateForm.tsx
	modified:   zlt-web/react-web/src/main/frontend/src/pages/device/Wayline/index.tsx
	deleted:    zlt-web/react-web/src/main/frontend/src/pages/device/Wayline1/components/UpdateForm.tsx
	deleted:    zlt-web/react-web/src/main/frontend/src/pages/device/Wayline1/index.less
	deleted:    zlt-web/react-web/src/main/frontend/src/pages/device/Wayline1/index.tsx
	modified:   zlt-web/react-web/src/main/frontend/src/pages/orders/OrderFile/index.tsx
	modified:   zlt-web/react-web/src/main/frontend/src/services/device/api.ts
	modified:   zlt-web/react-web/src/main/frontend/src/services/device/typings.d.ts
This commit is contained in:
2025-04-09 16:21:39 +08:00
parent 6bfbed5e4c
commit c727fc0c1f
39 changed files with 1575 additions and 614 deletions
+2 -1
View File
@@ -172,4 +172,5 @@ central-platform -- 父项目,公共依赖
1.全网唯一使用JavaAgent实现Http、MQ、Job全链路灰度 1.全网唯一使用JavaAgent实现Http、MQ、Job全链路灰度
2.全网唯一支持JavaAgent接入Sentinel 2.全网唯一支持JavaAgent接入Sentinel
+7
View File
@@ -64,6 +64,7 @@
<okhttp3.version>4.9.1</okhttp3.version> <okhttp3.version>4.9.1</okhttp3.version>
<glassfish-jaxb.version>2.3.3</glassfish-jaxb.version> <glassfish-jaxb.version>2.3.3</glassfish-jaxb.version>
<javax-jaxb.version>2.3.0</javax-jaxb.version> <javax-jaxb.version>2.3.0</javax-jaxb.version>
<easyexcel.version>3.3.3</easyexcel.version>
</properties> </properties>
<dependencies> <dependencies>
@@ -106,6 +107,12 @@
<artifactId>tomcat-embed-core</artifactId> <artifactId>tomcat-embed-core</artifactId>
<version>${tomcat-embed-core.version}</version> <version>${tomcat-embed-core.version}</version>
</dependency> </dependency>
<!-- EasyExcel依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>${easyexcel.version}</version>
</dependency>
</dependencies> </dependencies>
<dependencyManagement> <dependencyManagement>
+5
View File
@@ -89,6 +89,11 @@
<groupId>org.hibernate</groupId> <groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId> <artifactId>hibernate-validator</artifactId>
</dependency> </dependency>
<!-- 验证依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
@@ -1,20 +1,32 @@
package com.central.device.controller; package com.central.device.controller;
import java.util.Map; import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import lombok.RequiredArgsConstructor; import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.web.bind.annotation.*; import com.central.common.model.PageResult;
import io.swagger.v3.oas.annotations.tags.Tag; import com.central.common.model.Result;
import io.swagger.v3.oas.annotations.enums.ParameterIn; import com.central.device.model.AgeDevice;
import com.central.device.model.excel.AgeDeviceExcel;
import com.central.device.service.IAgeDeviceService;
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.Parameters; import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.central.device.model.AgeDevice; import java.io.IOException;
import com.central.device.service.IAgeDeviceService; import java.net.URLEncoder;
import com.central.common.model.PageResult; import java.nio.charset.StandardCharsets;
import com.central.common.model.Result; import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/** /**
* Device information * Device information
@@ -24,8 +36,8 @@ import com.central.common.model.Result;
*/ */
@Slf4j @Slf4j
@RestController @RestController
@RequestMapping("/age") @RequestMapping("/device")
@Tag(name = "Device information") @Tag(name = "设备管理")
@RequiredArgsConstructor @RequiredArgsConstructor
public class AgeDeviceController { public class AgeDeviceController {
private final IAgeDeviceService ageDeviceService; private final IAgeDeviceService ageDeviceService;
@@ -73,4 +85,185 @@ public class AgeDeviceController {
ageDeviceService.removeById(id); ageDeviceService.removeById(id);
return Result.succeed("删除成功"); return Result.succeed("删除成功");
} }
/**
* 导出设备信息
*/
@Operation(summary = "导出设备信息")
@PostMapping("/export")
public void exportDevices(@RequestBody Map<String, Object> params, HttpServletResponse response) {
try {
// 设置响应头
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
String fileName = URLEncoder.encode("设备信息", StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
// 查询导出数据
List<AgeDevice> deviceList = ageDeviceService.findListByParams(params);
if (CollUtil.isEmpty(deviceList)) {
deviceList = new ArrayList<>();
}
// 转换并写入Excel
List<AgeDeviceExcel> excelList = deviceList.stream()
.map(AgeDeviceExcel::fromDevice)
.collect(java.util.stream.Collectors.toList());
EasyExcel.write(response.getOutputStream(), AgeDeviceExcel.class)
.excelType(ExcelTypeEnum.XLSX)
.sheet("设备信息")
.doWrite(excelList);
} catch (Exception e) {
log.error("导出设备信息失败", e);
// 重置response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
try {
response.getWriter().println("{\"code\":500,\"msg\":\"导出失败\"}");
} catch (IOException ex) {
log.error("写入响应失败", ex);
}
}
}
/**
* 导入设备信息
*/
@Operation(summary = "导入设备信息")
@PostMapping("/import")
public Result<String> importDevices(@RequestParam("file") MultipartFile file) {
try {
if (file.isEmpty()) {
return Result.failed("请选择要导入的文件");
}
// 文件大小校验(10MB)
if (file.getSize() > 10 * 1024 * 1024) {
return Result.failed("文件大小不能超过10MB");
}
// 文件类型校验
String fileName = file.getOriginalFilename();
if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
return Result.failed("请上传Excel文件");
}
// 读取Excel数据
List<AgeDeviceExcel> excelList = EasyExcel.read(file.getInputStream())
.head(AgeDeviceExcel.class)
.sheet()
.doReadSync();
if (CollUtil.isEmpty(excelList)) {
return Result.failed("导入数据为空");
}
// 数据校验和转换
List<String> errorMsgs = new ArrayList<>();
List<AgeDevice> deviceList = new ArrayList<>();
for (int i = 0; i < excelList.size(); i++) {
AgeDeviceExcel excelData = excelList.get(i);
try {
// 数据校验
validateExcelData(excelData, i + 1, errorMsgs);
if (errorMsgs.isEmpty()) {
deviceList.add(excelData.toDevice());
}
} catch (Exception e) {
log.error("第{}行数据处理失败", i + 1, e);
errorMsgs.add(String.format("第%d行数据处理失败:%s", i + 1, e.getMessage()));
}
}
if (!errorMsgs.isEmpty()) {
return Result.failed("导入失败:" + String.join("; ", errorMsgs));
}
// 批量保存数据
boolean success = ageDeviceService.importDevices(deviceList);
return success ? Result.succeed("导入成功") : Result.failed("导入失败");
} catch (Exception e) {
log.error("导入设备信息失败", e);
return Result.failed("导入失败:" + e.getMessage());
}
}
@Operation(summary = "下载导入模板")
@GetMapping("/template")
public void downloadTemplate(HttpServletResponse response) {
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
String fileName = URLEncoder.encode("设备导入模板", StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
// 创建模板数据
List<AgeDeviceExcel> templateList = new ArrayList<>();
// 可以添加一行示例数据
AgeDeviceExcel template = new AgeDeviceExcel();
template.setDeviceSn("示例:DEVICE001");
template.setDeviceName("示例:测试设备1");
templateList.add(template);
EasyExcel.write(response.getOutputStream(), AgeDeviceExcel.class)
.excelType(ExcelTypeEnum.XLSX)
.sheet("设备信息")
.doWrite(templateList);
} catch (Exception e) {
log.error("下载模板失败", e);
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
try {
response.getWriter().println("{\"code\":500,\"msg\":\"下载模板失败\"}");
} catch (IOException ex) {
log.error("写入响应失败", ex);
}
}
}
/**
* 验证Excel数据
*/
private void validateExcelData(AgeDeviceExcel excelData, int rowIndex, List<String> errorMsgs) {
if (excelData == null) {
errorMsgs.add(String.format("第%d行数据为空", rowIndex));
return;
}
// 必填字段校验
if (org.springframework.util.StringUtils.isEmpty(excelData.getDeviceSn())) {
errorMsgs.add(String.format("第%d行:设备序列号不能为空", rowIndex));
}
if (org.springframework.util.StringUtils.isEmpty(excelData.getDeviceName())) {
errorMsgs.add(String.format("第%d行:设备名称不能为空", rowIndex));
}
// 字段格式校验
if (excelData.getDeviceType() != null && (excelData.getDeviceType() < 0 || excelData.getDeviceType() > 100)) {
errorMsgs.add(String.format("第%d行:设备类型取值范围为0-100", rowIndex));
}
// 重复性校验
if (!org.springframework.util.StringUtils.isEmpty(excelData.getDeviceSn())) {
boolean exists = ageDeviceService.checkDeviceSnExists(excelData.getDeviceSn());
if (exists) {
errorMsgs.add(String.format("第%d行:设备序列号已存在", rowIndex));
}
}
}
private List<AgeDeviceExcel> convertToExcelList(List<AgeDevice> deviceList) {
return deviceList.stream().map(device -> {
AgeDeviceExcel excel = new AgeDeviceExcel();
BeanUtils.copyProperties(device, excel);
return excel;
}).collect(Collectors.toList());
}
} }
@@ -7,10 +7,13 @@ import com.central.common.model.Result;
import com.central.device.feign.OrderCenterService; import com.central.device.feign.OrderCenterService;
import com.central.device.message.ControlEnum; import com.central.device.message.ControlEnum;
import com.central.device.message.ControlMessageConstant; import com.central.device.message.ControlMessageConstant;
import com.central.device.model.LineFile;
import com.central.device.service.ILineFileService;
import com.central.device.util.IotRequestResult; import com.central.device.util.IotRequestResult;
import com.central.device.util.MapUtil; import com.central.device.util.MapUtil;
import com.central.device.util.RequestUtils; import com.central.device.util.RequestUtils;
import com.central.device.util.http.HeaderUtils; import com.central.device.util.http.HeaderUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -47,6 +50,9 @@ public class ApiDeviceController {
@Autowired @Autowired
private OrderCenterService orderCenterService; private OrderCenterService orderCenterService;
@Autowired
private ILineFileService lineFileService;
/** /**
* 获取设备属性 * 获取设备属性
*/ */
@@ -69,53 +75,93 @@ public class ApiDeviceController {
*/ */
@Operation(summary = "设备属性设置") @Operation(summary = "设备属性设置")
@PostMapping("/setting/{deviceId}/property") @PostMapping("/setting/{deviceId}/property")
public Result writeProperties(@RequestBody Map<String,Object> param, @PathVariable("deviceId") String deviceId) throws IOException { public Result writeProperties(@RequestBody Map<String, Object> param, @PathVariable("deviceId") String deviceId) {
String url = baseUrl + "/device/instance/" + deviceId + "/property"; log.info("开始设置设备属性: deviceId={}, param={}", deviceId, param);
Gson gson = new Gson(); try {
JsonObject jsonObject; // 1. 参数校验
String property = MapUtil.getStrValue(param, "control"); String control = MapUtil.getStrValue(param, "control");
String value = MapUtil.getStrValue(param, "order_no"); String orderNo = MapUtil.getStrValue(param, "order_no");
Assert.notNull(value,"任务编号不能为空"); if (!validateParams(control, orderNo)) {
String orderStatus = orderCenterService.getOrderStatusByOrderNo(value); return Result.failed("参数错误");
if (!StringUtils.isEmpty(orderStatus)) { }
if (!orderStatus.equals("1")){
// 2. 检查订单状态
String orderStatus = orderCenterService.getOrderStatusByOrderNo(orderNo);
if (!isValidOrderStatus(orderStatus)) {
return Result.succeed("设备已执行"); return Result.succeed("设备已执行");
} }
}
try {
assert property != null;
if (ControlEnum.contains(ControlEnum.valueOf(property.toUpperCase()))) {
jsonObject = gson.fromJson(controlMessageConstant.CONTROL_MESSAGE_MAP.get(property), JsonObject.class);
JsonObject data = jsonObject.getAsJsonObject("data"); // 3. 构建控制消息
data.addProperty("order_no", value); JsonObject controlMessage = buildControlMessage(control, orderNo);
String waylinLinkUrl = orderCenterService.getOrderStatusByOrderNo(value); if (controlMessage == null) {
data.addProperty("wayline_link_url", waylinLinkUrl);
}else {
return Result.succeed("暂未开放控制权限"); return Result.succeed("暂未开放控制权限");
} }
Map<String, String> result = requestUtils.getPostRequestResultMap(url, jsonObject.toString());
JSONObject object = JSONObject.parseObject(result.get("")); // 4. 发送设备控制请求
Assert.notNull(object,"请求IOT平台异常"); String url = baseUrl + "/device/instance/" + deviceId + "/property";
IotRequestResult requestResult = IotRequestResult.getInstance(object); Map<String, String> result = requestUtils.getPostRequestResultMap(url, controlMessage.toString());
//500为设备回复超时
if (requestResult.getStatus() == 200 || requestResult.getStatus() == 500) { // 5. 处理响应结果
//更新订单状态为进行中 return handleDeviceResponse(result, orderNo);
Result result1 = orderCenterService.updateOrderStatusDoing(value);
if (result1.getResp_code() != null && result1.getResp_code() == 0){
return Result.succeed(result1.getData(),"设置成功");
}
}
return Result.failed("请重试");
} catch (Exception e) { } catch (Exception e) {
return Result.failed(e.getMessage()); log.error("设置设备属性异常: deviceId={}, error={}", deviceId, e.getMessage(), e);
return Result.failed("系统异常");
}
}
private boolean validateParams(String control, String orderNo) {
return !StringUtils.isEmpty(control) && !StringUtils.isEmpty(orderNo);
}
private boolean isValidOrderStatus(String orderStatus) {
return !StringUtils.isEmpty(orderStatus) && orderStatus.equals("1");
}
private JsonObject buildControlMessage(String control, String orderNo) {
if (!ControlEnum.contains(ControlEnum.valueOf(control.toUpperCase()))) {
return null;
} }
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(controlMessageConstant.CONTROL_MESSAGE_MAP.get(control), JsonObject.class);
JsonObject data = jsonObject.getAsJsonObject("data");
// 设置订单信息
data.addProperty("order_no", orderNo);
// 获取航线信息
Map<String, Object> wayResult = orderCenterService.getWaylineByOrderNo(orderNo);
String waylineFilePath = MapUtil.getStrValue(wayResult, "waylineFilePath");
String waylineId = MapUtil.getStrValue(wayResult, "waylineId");
data.addProperty("wayline_link_url", waylineFilePath);
LineFile lineFile = lineFileService.findLineFileByWaylineId(waylineId);
Assert.notNull(lineFile,"航线文件签名不正确");
data.addProperty("file_md5", lineFile.getSign());
return jsonObject;
} }
@GetMapping("/wayline") private Result handleDeviceResponse(Map<String, String> result, String orderNo) throws JsonProcessingException {
public Result<String> getWayline(@RequestParam String no){ JSONObject object = JSONObject.parseObject(result.get(""));
return Result.succeed(orderCenterService.getOrderStatusByOrderNo(no)); if (object == null) {
return Result.failed("请求IOT平台异常");
}
IotRequestResult requestResult = IotRequestResult.getInstance(object);
if (requestResult.getStatus() == 200 || requestResult.getStatus() == 500) {
Result updateResult = orderCenterService.updateOrderStatusDoing(orderNo);
if (updateResult.getResp_code() != null && updateResult.getResp_code() == 0) {
return Result.succeed(updateResult.getData(), "设置成功");
}
}
return Result.failed("请重试");
}
@GetMapping("/device/wayline")
public Result<Map> getWayline(@RequestParam String no){
return Result.succeed(orderCenterService.getWaylineByOrderNo(no));
} }
} }
@@ -47,11 +47,21 @@ public class LineFileController {
*/ */
@Operation(summary = "查询") @Operation(summary = "查询")
@GetMapping("/{id}") @GetMapping("/{id}")
public Result findById(@PathVariable Long id) { public Result findById(@PathVariable String id) {
LineFile model = lineFileService.getById(id); LineFile model = lineFileService.findLineFileByWaylineId(id);
return Result.succeed(model, "查询成功"); return Result.succeed(model, "查询成功");
} }
/**
* 查询
*/
@Operation(summary = "查询")
@GetMapping("/sign/{id}")
public String findLineSignById(@PathVariable String id) {
LineFile model = lineFileService.findLineFileByWaylineId(id);
return model.getSign();
}
/** /**
* 新增or更新 * 新增or更新
*/ */
@@ -9,6 +9,8 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import java.util.Map;
/** /**
* user-center模块远程调用 * user-center模块远程调用
* *
@@ -27,5 +29,5 @@ public interface OrderCenterService {
String getOrderStatusByOrderNo(@PathVariable("orderNo") String orderNo); String getOrderStatusByOrderNo(@PathVariable("orderNo") String orderNo);
@GetMapping("/qrcode/wayline/{orderNo}") @GetMapping("/qrcode/wayline/{orderNo}")
String getWaylineByOrderNo(@PathVariable("orderNo") String orderNo); Map<String,Object> getWaylineByOrderNo(@PathVariable("orderNo") String orderNo);
} }
@@ -6,6 +6,8 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Map;
/** /**
* 任务中心调用失败回调 * 任务中心调用失败回调
* *
@@ -33,8 +35,8 @@ public class OrderCenterServiceFallbackFactory implements FallbackFactory<OrderC
} }
@Override @Override
public String getWaylineByOrderNo(String orderNo) { public Map<String,Object> getWaylineByOrderNo(String orderNo) {
return ""; return null;
} }
}; };
} }
@@ -1,4 +1,73 @@
package com.central.device.model; package com.central.device.listener;
public class DeviceImportListener { import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.central.device.model.AgeDevice;
import com.central.device.model.excel.AgeDeviceExcel;
import com.central.device.service.IAgeDeviceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Slf4j
@RequiredArgsConstructor
public class DeviceImportListener implements ReadListener<AgeDeviceExcel> {
private final IAgeDeviceService deviceService;
private final List<AgeDevice> deviceList = new ArrayList<>();
private static final int BATCH_COUNT = 100;
@Override
public void invoke(AgeDeviceExcel data, AnalysisContext context) {
log.info("解析到一条数据: {}", data);
// 数据校验
validateData(data);
// 转换为实体
AgeDevice device = data.convertToDevice();
// 设置默认值
if (device.getCreateTime() == null) {
device.setCreateTime(new Date());
}
device.setUpdateTime(new Date());
deviceList.add(device);
if (deviceList.size() >= BATCH_COUNT) {
saveData();
deviceList.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
log.info("所有数据解析完成!");
}
private void validateData(AgeDeviceExcel data) {
if (StringUtils.isEmpty(data.getDeviceSn())) {
throw new IllegalArgumentException("设备序列号不能为空");
}
if (StringUtils.isEmpty(data.getDeviceName())) {
throw new IllegalArgumentException("设备名称不能为空");
}
// 检查设备序列号是否已存在
AgeDevice existDevice = deviceService.getByDeviceSn(data.getDeviceSn());
if (existDevice != null) {
throw new IllegalArgumentException("设备序列号已存在:" + data.getDeviceSn());
}
}
private void saveData() {
if (!deviceList.isEmpty()) {
log.info("开始保存数据,数量:{}", deviceList.size());
deviceService.saveBatch(deviceList);
}
}
} }
@@ -2,11 +2,12 @@ package com.central.device.model;
import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.central.common.model.SuperEntity;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import com.central.common.model.SuperEntity;
import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.EqualsAndHashCode;
import java.util.Date; import java.util.Date;
/** /**
@@ -20,7 +21,6 @@ import java.util.Date;
@EqualsAndHashCode(callSuper = false) @EqualsAndHashCode(callSuper = false)
@TableName("manage_device") @TableName("manage_device")
public class AgeDevice extends SuperEntity { public class AgeDevice extends SuperEntity {
private static final long serialVersionUID=1L;
private String deviceSn; private String deviceSn;
private String deviceName; private String deviceName;
@@ -45,4 +45,6 @@ public class AgeDevice extends SuperEntity {
private String deviceDesc; private String deviceDesc;
private String urlNormal; private String urlNormal;
private String urlSelect; private String urlSelect;
private String deviceStatus;
private String tenantId;
} }
@@ -2,11 +2,12 @@ package com.central.device.model;
import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.central.common.model.SuperEntity;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import com.central.common.model.SuperEntity;
import lombok.EqualsAndHashCode;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.EqualsAndHashCode;
import java.util.Date; import java.util.Date;
/** /**
@@ -36,4 +37,5 @@ public class LineFile extends SuperEntity {
private Date createTime; private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE) @TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime; private Date updateTime;
private String tenantId;
} }
@@ -1,4 +1,180 @@
package com.central.device.model; package com.central.device.model.excel;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.central.device.model.AgeDevice;
import com.fasterxml.jackson.annotation.JsonFormat;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* 设备信息Excel导入导出实体
*
* @author lsl
* @date 2024-12-19
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class AgeDeviceExcel { public class AgeDeviceExcel {
@ExcelProperty(value = "设备序列号", index = 0)
@ColumnWidth(20)
@NotBlank(message = "设备序列号不能为空")
private String deviceSn;
@ExcelProperty(value = "设备名称", index = 1)
@ColumnWidth(20)
@NotBlank(message = "设备名称不能为空")
private String deviceName;
@ExcelProperty(value = "设备类型", index = 2)
@ColumnWidth(15)
private Integer deviceType;
@ExcelProperty(value = "子类型", index = 3)
@ColumnWidth(15)
private Integer subType;
@ExcelProperty(value = "固件版本", index = 4)
@ColumnWidth(20)
private String firmwareVersion;
@ExcelProperty(value = "设备状态", index = 5)
@ColumnWidth(15)
private String deviceStatus;
@ExcelProperty(value = "设备描述", index = 6)
@ColumnWidth(30)
private String deviceDesc;
@ExcelProperty(value = "工作空间ID", index = 7)
@ColumnWidth(20)
private String workspaceId;
@ExcelProperty(value = "域", index = 8)
@ColumnWidth(15)
private Integer domain;
@ExcelProperty(value = "兼容状态", index = 9)
@ColumnWidth(15)
private Integer compatibleStatus;
@ExcelProperty(value = "版本", index = 10)
@ColumnWidth(15)
private String version;
@ExcelProperty(value = "设备索引", index = 11)
@ColumnWidth(20)
private String deviceIndex;
@ExcelProperty(value = "子设备序列号", index = 12)
@ColumnWidth(20)
private String childSn;
@ExcelProperty(value = "绑定状态", index = 13)
@ColumnWidth(15)
private Integer boundStatus;
@ExcelProperty(value = "租户ID", index = 14)
@ColumnWidth(20)
private String tenantId;
// 以下字段在Excel中不显示,但在实体转换时需要
@ExcelIgnore
private String userId;
@ExcelIgnore
private String nickname;
@ExcelIgnore
private Long boundTime;
@ExcelIgnore
private Long loginTime;
@ExcelIgnore
private String urlNormal;
@ExcelIgnore
private String urlSelect;
@ExcelProperty(value = "创建时间", index = 15)
@ColumnWidth(20)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@ExcelProperty(value = "更新时间", index = 16)
@ColumnWidth(20)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
/**
* 转换为设备实体
*/
public AgeDevice toDevice() {
AgeDevice device = new AgeDevice();
// 必填字段
device.setDeviceSn(this.deviceSn);
device.setDeviceName(this.deviceName);
device.setDeviceType(this.deviceType);
// 可选字段,需要判空
device.setSubType(this.subType);
device.setFirmwareVersion(this.firmwareVersion);
device.setDeviceStatus(this.deviceStatus);
device.setDeviceDesc(this.deviceDesc);
device.setWorkspaceId(this.workspaceId);
device.setDomain(this.domain);
device.setCompatibleStatus(this.compatibleStatus);
device.setVersion(this.version);
device.setDeviceIndex(this.deviceIndex);
device.setChildSn(this.childSn);
device.setBoundStatus(this.boundStatus);
device.setTenantId(this.tenantId);
// 系统字段
device.setCreateTime(this.createTime);
device.setUpdateTime(this.updateTime);
return device;
}
/**
* 从设备实体转换
*/
public static AgeDeviceExcel fromDevice(AgeDevice device) {
if (device == null) {
return null;
}
AgeDeviceExcel excel = new AgeDeviceExcel();
// 必填字段
excel.setDeviceSn(device.getDeviceSn());
excel.setDeviceName(device.getDeviceName());
excel.setDeviceType(device.getDeviceType());
// 可选字段
excel.setSubType(device.getSubType());
excel.setFirmwareVersion(device.getFirmwareVersion());
excel.setDeviceStatus(device.getDeviceStatus());
excel.setDeviceDesc(device.getDeviceDesc());
excel.setWorkspaceId(device.getWorkspaceId());
excel.setDomain(device.getDomain());
excel.setCompatibleStatus(device.getCompatibleStatus());
excel.setVersion(device.getVersion());
excel.setDeviceIndex(device.getDeviceIndex());
excel.setChildSn(device.getChildSn());
excel.setBoundStatus(device.getBoundStatus());
excel.setTenantId(device.getTenantId());
// 系统字段
excel.setCreateTime(device.getCreateTime());
excel.setUpdateTime(device.getUpdateTime());
return excel;
}
} }
@@ -4,6 +4,7 @@ import com.central.device.model.AgeDevice;
import com.central.common.model.PageResult; import com.central.common.model.PageResult;
import com.central.common.service.ISuperService; import com.central.common.service.ISuperService;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
@@ -19,5 +20,25 @@ public interface IAgeDeviceService extends ISuperService<AgeDevice> {
* @return * @return
*/ */
PageResult<AgeDevice> findList(Map<String, Object> params); PageResult<AgeDevice> findList(Map<String, Object> params);
/**
* 根据参数查询设备列表
*/
List<AgeDevice> findListByParams(Map<String, Object> params);
/**
* 根据设备序列号查询设备
*/
AgeDevice getByDeviceSn(String deviceSn);
/**
* 检查设备序列号是否存在
*/
boolean checkDeviceSnExists(String deviceSn);
/**
* 批量导入设备信息
*/
boolean importDevices(List<AgeDevice> deviceList);
} }
@@ -1,8 +1,8 @@
package com.central.device.service; package com.central.device.service;
import com.central.device.model.LineFile;
import com.central.common.model.PageResult; import com.central.common.model.PageResult;
import com.central.common.service.ISuperService; import com.central.common.service.ISuperService;
import com.central.device.model.LineFile;
import java.util.Map; import java.util.Map;
@@ -19,5 +19,7 @@ public interface ILineFileService extends ISuperService<LineFile> {
* @return * @return
*/ */
PageResult<LineFile> findList(Map<String, Object> params); PageResult<LineFile> findList(Map<String, Object> params);
LineFile findLineFileByWaylineId(String waylineId);
} }
@@ -1,5 +1,6 @@
package com.central.device.service.impl; package com.central.device.service.impl;
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.model.PageResult; import com.central.common.model.PageResult;
import com.central.common.service.impl.SuperServiceImpl; import com.central.common.service.impl.SuperServiceImpl;
@@ -9,6 +10,8 @@ import com.central.device.service.IAgeDeviceService;
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.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.collection.CollUtil;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -33,4 +36,53 @@ public class AgeDeviceServiceImpl extends SuperServiceImpl<AgeDeviceMapper, AgeD
List<AgeDevice> list = baseMapper.findList(page, params); List<AgeDevice> list = baseMapper.findList(page, params);
return PageResult.<AgeDevice>builder().data(list).resp_code(0).count(page.getTotal()).build(); return PageResult.<AgeDevice>builder().data(list).resp_code(0).count(page.getTotal()).build();
} }
@Override
public List<AgeDevice> findListByParams(Map<String, Object> params) {
QueryWrapper<AgeDevice> wrapper = new QueryWrapper<>();
// 添加查询条件
if (params.get("deviceSn") != null) {
wrapper.like("device_sn", params.get("deviceSn"));
}
if (params.get("deviceName") != null) {
wrapper.like("device_name", params.get("deviceName"));
}
if (params.get("deviceType") != null) {
wrapper.eq("device_type", params.get("deviceType"));
}
// 可以添加更多查询条件...
return this.list(wrapper);
}
@Override
public AgeDevice getByDeviceSn(String deviceSn) {
return this.getOne(new QueryWrapper<AgeDevice>().eq("device_sn", deviceSn));
}
@Override
public boolean checkDeviceSnExists(String deviceSn) {
return this.baseMapper.exists(new QueryWrapper<AgeDevice>()
.eq("device_sn", deviceSn));
}
@Transactional(rollbackFor = Exception.class)
@Override
public boolean importDevices(List<AgeDevice> deviceList) {
if (CollUtil.isEmpty(deviceList)) {
return false;
}
try {
// 批量保存,每批100条
int batchSize = 100;
List<List<AgeDevice>> partition = CollUtil.partition(deviceList, batchSize);
for (List<AgeDevice> batch : partition) {
this.saveBatch(batch, batchSize);
}
return true;
} catch (Exception e) {
log.error("批量导入设备信息失败", e);
throw new RuntimeException("批量导入设备信息失败", e);
}
}
} }
@@ -1,5 +1,6 @@
package com.central.device.service.impl; package com.central.device.service.impl;
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.model.PageResult; import com.central.common.model.PageResult;
import com.central.common.service.impl.SuperServiceImpl; import com.central.common.service.impl.SuperServiceImpl;
@@ -33,4 +34,10 @@ public class LineFileServiceImpl extends SuperServiceImpl<LineFileMapper, LineFi
List<LineFile> list = baseMapper.findList(page, params); List<LineFile> list = baseMapper.findList(page, params);
return PageResult.<LineFile>builder().data(list).resp_code(0).count(page.getTotal()).build(); return PageResult.<LineFile>builder().data(list).resp_code(0).count(page.getTotal()).build();
} }
@Override
public LineFile findLineFileByWaylineId(String waylineId) {
return baseMapper.selectOne(new QueryWrapper<LineFile>()
.eq("wayline_id",waylineId));
}
} }
@@ -5,6 +5,7 @@ import com.central.common.model.PageResult;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.file.service.IFileService; import com.central.file.service.IFileService;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils; import org.apache.commons.collections.MapUtils;
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;
@@ -26,6 +27,7 @@ import java.util.Map;
* *
* @author 作者 owen E-mail: 624191343@qq.com * @author 作者 owen E-mail: 624191343@qq.com
*/ */
@Slf4j
@RestController @RestController
public class FileController { public class FileController {
@Autowired @Autowired
@@ -103,7 +105,10 @@ public class FileController {
@GetMapping("/file/{id}") @GetMapping("/file/{id}")
public String getFileViewUrl(@PathVariable String id) { public String getFileViewUrl(@PathVariable String id) {
return fileService.getViewUrl(id); log.info("请求文件可访问链接,参数文件Id:{}",id);
String viewUrl = fileService.getViewUrl(id);
log.info("请求文件可访问链接,链接值:{}",viewUrl);
return viewUrl;
} }
@GetMapping("/files/{id}") @GetMapping("/files/{id}")
@@ -8,8 +8,10 @@ import com.central.common.model.FileInfo;
import com.central.oss.model.ObjectInfo; import com.central.oss.model.ObjectInfo;
import com.central.oss.properties.FileServerProperties; import com.central.oss.properties.FileServerProperties;
import com.central.oss.template.OssTemplate; import com.central.oss.template.OssTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource; import javax.annotation.Resource;
@@ -22,6 +24,7 @@ import java.io.OutputStream;
* @date 2025/1/13 * @date 2025/1/13
* <p> * <p>
*/ */
@Slf4j
@Service @Service
@ConditionalOnProperty(prefix = FileServerProperties.PREFIX, name = "type", havingValue = FileServerProperties.TYPE_OSS) @ConditionalOnProperty(prefix = FileServerProperties.PREFIX, name = "type", havingValue = FileServerProperties.TYPE_OSS)
public class OssService extends AbstractIFileService { public class OssService extends AbstractIFileService {
@@ -87,7 +90,25 @@ public class OssService extends AbstractIFileService {
@Override @Override
public FileInfo getFileInfo(String id) { public FileInfo getFileInfo(String id) {
return baseMapper.findById(id); if (StringUtils.isEmpty(id)) {
log.warn("文件ID为空");
return null;
}
try {
log.info("开始查询文件信息: fileId={}", id);
FileInfo fileInfo = baseMapper.selectById(id.trim()); // 添加trim()去除可能的空格
if (fileInfo == null) {
log.warn("未找到文件信息: fileId={}", id);
return null;
}
log.info("查询文件信息成功: fileId={}, path={}", fileInfo.getId(), fileInfo.getPath());
return fileInfo;
} catch (Exception e) {
log.error("查询文件信息异常: fileId={}, error={}", id, e.getMessage(), e);
throw new RuntimeException("查询文件信息失败", e);
}
} }
@Override @Override
@@ -47,7 +47,7 @@ zlt:
bucketName: ${zlt.oss.bucketName} bucketName: ${zlt.oss.bucketName}
#多租户配置 #多租户配置
tenant: tenant:
enable: true enable: false
#fastDFS配置 #fastDFS配置
#fdfs: #fdfs:
@@ -12,6 +12,7 @@ import com.central.log.annotation.AuditLog;
import com.central.order.config.TencentPayProperties; import com.central.order.config.TencentPayProperties;
import com.central.order.enums.CommonStatus; import com.central.order.enums.CommonStatus;
import com.central.order.enums.OrderStatus; import com.central.order.enums.OrderStatus;
import com.central.order.feign.DeviceCenterService;
import com.central.order.feign.FileCenterService; import com.central.order.feign.FileCenterService;
import com.central.order.feign.UserCenterService; import com.central.order.feign.UserCenterService;
import com.central.order.model.*; import com.central.order.model.*;
@@ -93,6 +94,11 @@ public class OrderController {
// 获取当前日期,格式化为 yyyyMMdd // 获取当前日期,格式化为 yyyyMMdd
SimpleDateFormat sdf = new SimpleDateFormat(CommonConstant.DATEMINUTE_FORMAT); SimpleDateFormat sdf = new SimpleDateFormat(CommonConstant.DATEMINUTE_FORMAT);
@Autowired
private DeviceCenterService deviceCenterService;
/** /**
* 列表 * 列表
*/ */
@@ -335,7 +341,19 @@ public class OrderController {
if (orderService.getUnCompleteOrderCount(deviceSn)==0){ if (orderService.getUnCompleteOrderCount(deviceSn)==0){
List<Order> orders = orderService.getOrdersInQueueByDevice(deviceSn); List<Order> orders = orderService.getOrdersInQueueByDevice(deviceSn);
if (!orders.isEmpty()){ if (!orders.isEmpty()){
return Result.succeed(orders.get(0),"获取成功"); Order order = orders.get(0);
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
Assert.notNull(qrCode,"二维码数据不能为空");
// 从二维码中获取航线ID
String waylineId = qrCode.getWaylineId();
// 根据航线ID获取对应的文件路径
String waylineFilePath = fileCenterService.getFileViewUrl(waylineId);
Assert.notNull(waylineFilePath,"订单航线数据不能为空");
order.setFileMd5(deviceCenterService.getLineFileSign(waylineId));
order.setWaylineLinkUrl(waylineFilePath);
return Result.succeed(order,"获取成功");
} }
} }
return Result.failed("未存在排队队列"); return Result.failed("未存在排队队列");
@@ -20,6 +20,7 @@ import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
@@ -133,13 +134,16 @@ public class QrCodeController {
} }
@GetMapping("/wayline/{orderNo}") @GetMapping("/wayline/{orderNo}")
public String getWaylineByOrderNo(@PathVariable("orderNo") String orderNo){ public Map<String,Object> getWaylineByOrderNo(@PathVariable("orderNo") String orderNo){
Order order = orderService.getOrderByNumber(orderNo); Order order = orderService.getOrderByNumber(orderNo);
Assert.notNull(order,"订单No不能为空"); Assert.notNull(order,"订单No不能为空");
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId()); QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
Assert.notNull(qrCode,"二维码数据不能为空"); Assert.notNull(qrCode,"二维码数据不能为空");
String waylineFilePath = fileCenterService.getFileViewUrl(qrCode.getWaylineId()); String waylineFilePath = fileCenterService.getFileViewUrl(qrCode.getWaylineId());
return waylineFilePath; Map<String,Object> map = new HashMap<>();
map.put("waylineFilePath",waylineFilePath);
map.put("waylineId",qrCode.getWaylineId());
return map;
} }
} }
@@ -1,46 +1,29 @@
package com.central.order.feign; package com.central.order.feign;
import com.central.common.constant.ServiceNameConstants; import com.central.common.constant.ServiceNameConstants;
import com.central.common.model.FileInfo; import com.central.order.feign.fallback.DeviceCenterServiceFallbackFactory;
import com.central.common.model.Result;
import com.central.order.feign.fallback.FileCenterServiceFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.Map;
/** /**
* user-center模块远程调用 * device-center模块远程调用
* *
* @author lsl * @author lsl
* @version 1.0 * @version 1.0
* @description user-center模块远程调用 * @description user-center模块远程调用
* @create 2025/1/13 * @create 2025/1/13
**/ **/
@FeignClient(name = ServiceNameConstants.FILE_SERVICE, fallbackFactory = FileCenterServiceFallbackFactory.class, dismiss404 = true) @FeignClient(name = ServiceNameConstants.DEVICE_SERVICE, fallbackFactory = DeviceCenterServiceFallbackFactory.class, dismiss404 = true)
public interface FileCenterService { public interface DeviceCenterService {
/** /**
* 通过ID查询预览地址 * 通过ID查询文件sign
* *
* @param id 文件ID * @param id 文件ID
* @return * @return
*/ */
@GetMapping("/file/{id}") @GetMapping("/wayline/sign/{id}")
String getFileViewUrl(@PathVariable("id") String id); String getLineFileSign(@PathVariable("id") String id);
@GetMapping("/type/{id}")
String getFileContentType(@PathVariable("id") String id);
@GetMapping("/qrcode/{codeId}")
Result<Map> uploadQrCodeFile(@PathVariable("codeId") String codeId) throws Exception;
@PostMapping("/path")
FileInfo creatFileInfo(@RequestBody String path);
@GetMapping("/files/path")
String getViewUrlByPath(@RequestParam("path") String path) ;
@GetMapping("/files/path/style")
String getViewUrlByPathStyle(@RequestParam("params") Map<String,String> params) ;
} }
@@ -1,60 +1,30 @@
package com.central.order.feign.fallback; package com.central.order.feign.fallback;
import com.central.common.model.FileInfo; import com.central.order.feign.DeviceCenterService;
import com.central.common.model.Result;
import com.central.order.feign.FileCenterService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Map;
/** /**
* 文件中心调用失败回调 * 文件中心调用失败回调
* *
* @author lsl * @author lsl
* @version 1.0 * @version 1.0
* @description 用户中心调用失败回调 * @description 设备中心调用失败回调
* @create 2025/1/17 11:33 * @create 2025/1/17 11:33
**/ **/
@Slf4j @Slf4j
@Component @Component
public class FileCenterServiceFallbackFactory implements FallbackFactory<FileCenterService> { public class DeviceCenterServiceFallbackFactory implements FallbackFactory<DeviceCenterService> {
@Override @Override
public FileCenterService create(Throwable cause) { public DeviceCenterService create(Throwable cause) {
return new FileCenterService() { return new DeviceCenterService() {
@Override @Override
public String getFileViewUrl(String id) { public String getLineFileSign(String id) {
return ""; return "";
} }
@Override
public String getFileContentType(String id) {
return "";
}
@Override
public Result<Map> uploadQrCodeFile(String codeId) throws Exception {
return null;
}
@Override
public FileInfo creatFileInfo(String path) {
return null;
}
@Override
public String getViewUrlByPath(String path) {
return "";
}
@Override
public String getViewUrlByPathStyle(Map<String, String> params) {
return "";
}
}; };
} }
} }
@@ -37,6 +37,7 @@ public class Order extends SuperEntity {
private Date payTime; private Date payTime;
private transient String createdTime; private transient String createdTime;
private transient String fileMd5;
private String codeId; private String codeId;
@TableField(fill = FieldFill.INSERT) @TableField(fill = FieldFill.INSERT)
@@ -48,5 +49,7 @@ public class Order extends SuperEntity {
private String company; private String company;
private Integer isDel; private Integer isDel;
private transient String waylineLinkUrl;
} }
@@ -23,7 +23,6 @@ import java.util.Date;
@Getter @Getter
@Setter @Setter
public class FileInfo extends Model<FileInfo> { public class FileInfo extends Model<FileInfo> {
private static final long serialVersionUID = -1438078028040922174L;
@TableId @TableId
private String id; private String id;
@@ -71,7 +71,7 @@ export default defineConfig({
}, },
], ],
nodeModulesTransform: { type: 'none' }, nodeModulesTransform: { type: 'none' },
mfsu: {}, mfsu: false,
webpack5: {}, webpack5: {},
exportStatic: {}, exportStatic: {},
history: { history: {
@@ -54,6 +54,10 @@
path: '/device/wayline.html', path: '/device/wayline.html',
component: './device/Wayline', component: './device/Wayline',
}, },
{
path: '/device/device.html',
component: './device/Device',
},
] ]
}, },
{ {
@@ -13,7 +13,7 @@ server {
root /usr/share/nginx/html; root /usr/share/nginx/html;
index index.html; index index.html;
# 重要:确保所有路由都指向 index.html # 支持 history 路由
location / { location / {
try_files $uri $uri/ /index.html; try_files $uri $uri/ /index.html;
@@ -48,6 +48,7 @@
"@ant-design/charts": "^1.4.2", "@ant-design/charts": "^1.4.2",
"@ant-design/icons": "^4.7.0", "@ant-design/icons": "^4.7.0",
"@ant-design/pro-components": "1.1.1", "@ant-design/pro-components": "1.1.1",
"@babel/runtime": "^7.27.0",
"@umijs/route-utils": "^2.0.0", "@umijs/route-utils": "^2.0.0",
"antd": "^4.20.0", "antd": "^4.20.0",
"classnames": "^2.3.0", "classnames": "^2.3.0",
@@ -63,6 +64,7 @@
"react-helmet-async": "^1.2.0", "react-helmet-async": "^1.2.0",
"react-intl": "6.4.4", "react-intl": "6.4.4",
"react-json-tree": "^0.17.0", "react-json-tree": "^0.17.0",
"spark-md5": "^3.0.2",
"treeify-js": "^1.0.8", "treeify-js": "^1.0.8",
"umi": "^3.5.0", "umi": "^3.5.0",
"uuid": "^9.0.0" "uuid": "^9.0.0"
@@ -0,0 +1,86 @@
import {
ModalForm,
ProForm,
ProFormSelect,
ProFormText,
ProFormTextArea,
} from '@ant-design/pro-components';
import React from 'react';
interface UpdateFormProps {
onSubmit: (values: DEVICE.Device) => Promise<boolean>;
onVisibleChange: (visible: boolean) => void;
updateModalVisible: boolean;
values?: DEVICE.Device;
}
const UpdateForm: React.FC<UpdateFormProps> = (props) => {
const { onSubmit, onVisibleChange, updateModalVisible, values } = props;
return (
<ModalForm
title="修改设备信息"
width="800px"
visible={updateModalVisible}
onVisibleChange={onVisibleChange}
onFinish={onSubmit}
initialValues={values}
>
<ProForm.Group>
<ProFormText
disabled
width="md"
name="deviceSn"
label="设备序列号"
/>
<ProFormText
rules={[{ required: true, message: '设备名称不能为空' }]}
width="md"
name="deviceName"
label="设备名称"
/>
</ProForm.Group>
<ProForm.Group>
<ProFormText
width="md"
name="nickname"
label="昵称"
/>
<ProFormSelect
rules={[{ required: true, message: '工作区不能为空' }]}
width="md"
name="workspaceId"
label="工作区"
options={[
{ label: '工作区1', value: '1' },
{ label: '工作区2', value: '2' },
]}
/>
</ProForm.Group>
<ProForm.Group>
<ProFormSelect
rules={[{ required: true, message: '设备类型不能为空' }]}
width="md"
name="deviceType"
label="设备类型"
options={[
{ label: '类型1', value: 0 },
{ label: '类型2', value: 1 },
]}
/>
<ProFormText
width="md"
name="firmwareVersion"
label="固件版本"
/>
</ProForm.Group>
<ProFormTextArea
name="deviceDesc"
label="设备描述"
placeholder="请输入设备描述"
/>
</ModalForm>
);
};
export default UpdateForm;
@@ -0,0 +1,394 @@
import {
device,
saveOrUpdateDevice,
deleteDevice,
updateDeviceBoundStatus,
} from '@/services/device/api';
import { PlusOutlined, ExportOutlined, ImportOutlined, DownloadOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
ModalForm,
PageContainer,
ProForm,
ProFormText,
ProFormSelect,
ProFormTextArea,
ProTable,
QueryFilter,
} from '@ant-design/pro-components';
import { Button, message, Popconfirm, Typography, Space, Switch, Upload } from 'antd';
import type { RcFile } from 'antd/lib/upload';
import React, { useRef, useState } from 'react';
import moment from 'moment';
import UpdateForm from './components/UpdateForm';
const { Link } = Typography;
// 定义常量对象而不是使用命名空间
const DEVICE_TYPE = {
DOCK: 1,
DRONE: 2,
REMOTE_CONTROL: 3,
} as const;
const BOUND_STATUS = {
UNBOUND: 0,
BOUND: 1,
} as const;
const COMPATIBLE_STATUS = {
INCONSISTENT: 0,
CONSISTENT: 1,
} as const;
const TableList: React.FC = () => {
const [searchParams, setSearchParams] = useState<Record<string, string | number>>({});
const actionRef = useRef<ActionType>();
const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
const [currentRow, setCurrentRow] = useState<DEVICE.Device>();
// 统一的API请求处理函数
const handleRequest = async (
action: () => Promise<any>,
loadingMessage: string,
successMessage: string,
) => {
const hide = message.loading(loadingMessage);
try {
const result = await action();
hide();
if (result.resp_code === 0) {
message.success(successMessage);
return true;
}
message.error(result.resp_msg);
return false;
} catch (error) {
hide();
message.error(`${successMessage}失败`);
return false;
}
};
// 切换设备绑定状态
const switchBoundStatus = async (record: DEVICE.Device) => {
const success = await handleRequest(
() => updateDeviceBoundStatus(record.deviceSn, record.boundStatus === 1 ? 0 : 1),
'正在更新',
'更新成功'
);
if (success && actionRef.current) {
actionRef.current.reload();
}
};
// 处理导出
const handleExport = async () => {
const hide = message.loading('正在导出...');
try {
const response = await fetch('/api-device/device/export', {
method: 'POST',
});
if (response.ok) {
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `设备信息_${moment().format('YYYY-MM-DD')}.xlsx`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
message.success('导出成功');
} else {
throw new Error('导出失败');
}
} catch (error) {
message.error('导出失败');
} finally {
hide();
}
};
// 下载模板
const handleDownloadTemplate = () => {
window.location.href = '/api-device/device/template';
};
const columns: ProColumns<DEVICE.Device>[] = [
{
dataIndex: 'index',
valueType: 'indexBorder',
},
{
title: '设备序列号',
dataIndex: 'deviceSn',
copyable: true,
fixed: 'left',
},
{
title: '设备名称',
dataIndex: 'deviceName',
},
{
title: '昵称',
dataIndex: 'nickname',
},
{
title: '设备类型',
dataIndex: 'deviceType',
valueType: 'select',
valueEnum: {
[DEVICE_TYPE.DOCK]: { text: '机场' },
[DEVICE_TYPE.DRONE]: { text: '无人机' },
[DEVICE_TYPE.REMOTE_CONTROL]: { text: '遥控器' },
},
},
{
title: '固件版本',
dataIndex: 'firmwareVersion',
},
{
title: '固件状态',
dataIndex: 'compatibleStatus',
valueType: 'select',
valueEnum: {
[COMPATIBLE_STATUS.CONSISTENT]: { text: '一致', status: 'Success' },
[COMPATIBLE_STATUS.INCONSISTENT]: { text: '不一致', status: 'Error' },
},
},
{
title: '绑定状态',
dataIndex: 'boundStatus',
render: (_, record) => (
<Switch
checkedChildren="已绑定"
unCheckedChildren="未绑定"
checked={record.boundStatus === 1}
onClick={() => switchBoundStatus(record)}
/>
),
},
{
title: '最后登录',
dataIndex: 'loginTime',
valueType: 'dateTime',
render: (text) => (text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '-'),
},
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateTime',
render: (text) => (text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '-'),
},
{
title: '操作',
key: 'action',
render: (_, record) => (
<Space>
<Link
onClick={() => {
setCurrentRow(record);
setUpdateModalVisible(true);
}}
>
修改
</Link>
<Popconfirm
title={`确认删除设备[${record.deviceSn}]?`}
onConfirm={async () => {
const success = await handleRequest(
() => deleteDevice(record.deviceSn),
'正在删除',
'删除成功'
);
if (success && actionRef.current) {
actionRef.current.reload();
}
}}
>
<Link>删除</Link>
</Popconfirm>
</Space>
),
},
];
// 表单字段定义
const renderModalContent = () => (
<ProForm.Group>
<ProFormText
rules={[{ required: true, message: '设备序列号不能为空' }]}
width="md"
name="deviceSn"
label="设备序列号"
/>
<ProFormText
rules={[{ required: true, message: '设备名称不能为空' }]}
width="md"
name="deviceName"
label="设备名称"
/>
<ProFormText
rules={[{ required: true, message: '设备昵称不能为空' }]}
width="md"
name="nickname"
label="设备昵称"
/>
<ProFormSelect
rules={[{ required: true, message: '设备类型不能为空' }]}
width="md"
name="deviceType"
label="设备类型"
options={[
{ label: '机场', value: DEVICE_TYPE.DOCK },
{ label: '无人机', value: DEVICE_TYPE.DRONE },
{ label: '遥控器', value: DEVICE_TYPE.REMOTE_CONTROL },
]}
/>
<ProFormSelect
width="md"
name="subType"
label="设备子类型"
options={[
// 根据实际需求添加子类型选项
]}
/>
<ProFormText
width="md"
name="firmwareVersion"
label="固件版本"
/>
<ProFormTextArea
name="deviceDesc"
label="设备描述"
placeholder="请输入设备描述"
/>
</ProForm.Group>
);
return (
<PageContainer header={{ subTitle: '管理系统中的设备' }}>
<QueryFilter
defaultCollapsed
split
className="query-filter"
onFinish={async (values) => setSearchParams(values)}
>
<ProFormSelect
name="searchKey"
label="搜索"
valueEnum={{
deviceSn: '设备序列号',
deviceName: '设备名称',
nickname: '昵称',
}}
/>
<ProFormText name="searchValue" />
</QueryFilter>
<ProTable<DEVICE.Device>
rowKey="deviceSn"
headerTitle="设备管理"
actionRef={actionRef}
request={device}
columns={columns}
search={false}
params={searchParams}
pagination={{
showSizeChanger: true,
showQuickJumper: true,
}}
toolBarRender={() => [
<Button
key="template"
onClick={handleDownloadTemplate}
>
<DownloadOutlined /> 下载模板
</Button>,
<Button
key="export"
onClick={handleExport}
>
<ExportOutlined /> 导出
</Button>,
<Upload
key="import"
name="file"
accept=".xlsx,.xls"
maxCount={1}
action="/api-device/device/import"
showUploadList={false}
onChange={(info) => {
if (info.file.status === 'uploading') {
message.loading('正在导入...');
}
if (info.file.status === 'done') {
if (info.file.response.resp_code === 0) {
message.success('导入成功');
// 刷新表格数据
actionRef.current?.reload();
} else {
message.error(info.file.response.resp_msg || '导入失败');
}
} else if (info.file.status === 'error') {
message.error('导入失败');
}
}}
>
<Button>
<ImportOutlined /> 导入
</Button>
</Upload>,
<Button
type="primary"
key="add"
onClick={() => setCreateModalVisible(true)}
>
<PlusOutlined /> 新增
</Button>,
]}
/>
<ModalForm
title="新增设备"
width="800px"
visible={createModalVisible}
onVisibleChange={setCreateModalVisible}
onFinish={async (values) => {
const success = await handleRequest(
() => saveOrUpdateDevice(values as DEVICE.Device),
'正在添加',
'添加成功',
);
if (success) {
setCreateModalVisible(false);
actionRef.current?.reload();
}
return success;
}}
>
{renderModalContent()}
</ModalForm>
<UpdateForm
onSubmit={async (values) => {
const success = await handleRequest(
() => saveOrUpdateDevice({ ...currentRow, ...values }),
'正在更新',
'更新成功',
);
if (success) {
setUpdateModalVisible(false);
setCurrentRow(undefined);
actionRef.current?.reload();
}
return success;
}}
onVisibleChange={setUpdateModalVisible}
updateModalVisible={updateModalVisible}
values={currentRow}
/>
</PageContainer>
);
};
export default TableList;
@@ -8,9 +8,10 @@ import {
} from '@ant-design/pro-components'; } from '@ant-design/pro-components';
import { Button, Form, message, Upload } from 'antd'; import { Button, Form, message, Upload } from 'antd';
import { RcFile } from 'antd/lib/upload'; import { RcFile } from 'antd/lib/upload';
import { useState } from 'react'; import { useState, useRef, useEffect } from 'react';
import styles from '../index.less'; import styles from '../index.less';
import { TOURISM_OPTIONS, TYPE_OPTIONS, WORKSPACE_OPTIONS } from '../index'; import { TOURISM_OPTIONS, TYPE_OPTIONS, WORKSPACE_OPTIONS } from '../index';
import SparkMD5 from 'spark-md5';
export type FormValueType = Partial<ORDERS.TourismFile>; export type FormValueType = Partial<ORDERS.TourismFile>;
@@ -22,97 +23,156 @@ export type UpdateFormProps = {
onUpload: (fileInfo: FileResponse) => void; onUpload: (fileInfo: FileResponse) => void;
}; };
const handleImport = async (file: RcFile) => { const calculateFileMD5 = (file: File): Promise<string> => {
const hide = message.loading('正在导入'); return new Promise((resolve, reject) => {
try { const reader = new FileReader();
const formData = new FormData(); const spark = new SparkMD5.ArrayBuffer();
formData.append('file', file);
const result = await importImage(formData); reader.onload = (e) => {
hide(); if (e.target?.result) {
message.success('上传素材成功'); spark.append(e.target.result as ArrayBuffer);
return result; const md5 = spark.end();
} catch (error) { resolve(md5);
hide(); } else {
message.error('上传素材失败'); reject(new Error('Failed to read file'));
return null; }
} };
reader.onerror = (error) => reject(error);
reader.readAsArrayBuffer(file);
});
}; };
const UpdateForm: React.FC<UpdateFormProps> = (props) => { const UpdateForm: React.FC<UpdateFormProps> = (props) => {
const { onSubmit, onVisibleChange, updateModalVisible, values, onUpload } = props; const { onSubmit, onVisibleChange, updateModalVisible, values, onUpload } = props;
const [hasNewFile, setHasNewFile] = useState(false); const [fileInfo, setFileInfo] = useState<FileResponse | undefined>();
const formRef = useRef<any>();
// 确保所有的hooks都在组件顶层
useEffect(() => {
if (values) {
formRef.current?.setFieldsValue(values);
}
}, [values]);
const handleFileUpload = async (file: RcFile) => {
const hide = message.loading('正在上传文件...');
try {
const sign = await calculateFileMD5(file);
console.log('新文件签名:', sign);
const formData = new FormData();
formData.append('file', file);
formData.append('sign', sign);
const result = await importImage(formData);
console.log('上传接口返回结果:', result);
if (!result || !result.id) {
hide();
message.error('上传失败:未获取到文件信息');
return false;
}
const newFileInfo = {
id: result.id,
name: result.name || file.name,
url: result.url || '',
sign: sign
};
setFileInfo(newFileInfo);
formRef.current?.setFieldsValue({
waylineId: newFileInfo.id,
name: newFileInfo.name,
sign: newFileInfo.sign
});
onUpload?.(newFileInfo);
hide();
message.success('文件上传成功');
return false;
} catch (error: any) {
hide();
console.error('文件上传错误:', error);
message.error('文件上传失败:' + (error?.message || '未知错误'));
return false;
}
};
return ( return (
<ModalForm <ModalForm
title="修改航线" title="修改航线"
formRef={formRef}
visible={updateModalVisible} visible={updateModalVisible}
onVisibleChange={(visible) => { onVisibleChange={(visible) => {
onVisibleChange(visible); onVisibleChange?.(visible);
if (!visible) { if (!visible) {
setHasNewFile(false); setFileInfo(undefined);
} }
}} }}
modalProps={{ destroyOnClose: true }} onFinish={async (values) => {
onFinish={async (formValues) => { if (onSubmit) {
// 只提交已修改的字段 const updatedValues = {
const changedValues: Partial<DEVICE.Wayline> = {}; ...values,
Object.keys(formValues).forEach(key => { ...(fileInfo ? {
if (formValues[key] !== values?.[key]) { waylineId: fileInfo.id,
changedValues[key] = formValues[key]; sign: fileInfo.sign
} } : {})
}); };
return onSubmit(updatedValues);
if (Object.keys(changedValues).length === 0 && !hasNewFile) {
return true;
} }
return false;
await onSubmit(changedValues);
}} }}
initialValues={values}
> >
<ProForm.Group> <ProForm.Group>
<ProFormText <ProFormText
rules={[{ required: true, message: '航线名称不能为空' }]}
width="md" width="md"
name="name" name="name"
label="航线名称" label="航线名称"
placeholder="请输入航线名称"
rules={[{ required: true, message: '航线名称不能为空' }]}
/> />
<ProFormSelect <ProFormSelect
rules={[{ required: true, message: '工作区不能为空' }]}
width="md" width="md"
name="workspaceId" name="workspaceId"
label="工作区" label="工作区"
placeholder="请选择工作区"
options={WORKSPACE_OPTIONS} options={WORKSPACE_OPTIONS}
rules={[{ required: true, message: '工作区不能为空' }]}
/> />
<ProFormText
<div style={{ width: '328px' }}> hidden
name="waylineId"
/>
<ProFormText
hidden
name="sign"
/>
</ProForm.Group>
<ProForm.Group>
<div style={{ width: '328px', marginBottom: 24 }}>
<div style={{ marginBottom: 8 }}>航线文件:</div> <div style={{ marginBottom: 8 }}>航线文件:</div>
{values?.fileUrl && !hasNewFile && (
<div style={{ marginBottom: 8 }}>
当前文件:{values.name}
</div>
)}
<Upload <Upload
maxCount={1} maxCount={1}
action="/api-file/files-anon" accept=".kmz,.kml"
showUploadList={false} showUploadList={false}
beforeUpload={async (file) => { beforeUpload={handleFileUpload}
const result = await handleImport(file);
if (result) {
onUpload(result);
setHasNewFile(true);
message.success('文件上传成功');
}
return false;
}}
> >
<Button icon={<UploadOutlined />}> <Button icon={<UploadOutlined />}>
{hasNewFile ? '重新上传' : '上传文件'} 重新上传航线文件
</Button> </Button>
</Upload> </Upload>
{hasNewFile && <div style={{ marginTop: 8, color: '#52c41a' }}>已上传新文件</div>} {fileInfo && (
<div style={{ marginTop: 8 }}>
<div style={{ color: '#52c41a' }}>
已上传:{fileInfo.name}
</div>
<div style={{ color: '#666', fontSize: '12px' }}>
文件签名:{fileInfo.sign}
</div>
</div>
)}
</div> </div>
</ProForm.Group> </ProForm.Group>
</ModalForm> </ModalForm>
@@ -16,6 +16,8 @@ import type { RcFile } from 'antd/lib/upload';
import React, { useRef, useState, useCallback } from 'react'; import React, { useRef, useState, useCallback } from 'react';
import UpdateForm from './components/UpdateForm'; import UpdateForm from './components/UpdateForm';
import styles from './index.less'; import styles from './index.less';
import SparkMD5 from 'spark-md5';
import { DefaultOptionType } from 'antd/es/select';
const { Link } = Typography; const { Link } = Typography;
@@ -26,11 +28,11 @@ const statusColorMap = {
}; };
// 提取常量 // 提取常量
export const WORKSPACE_OPTIONS = [ const WORKSPACE_OPTIONS: DefaultOptionType[] = [
{ label: '工作区1', value: 1 }, { label: '工作区1', value: '1' },
{ label: '工作区2', value: 2 }, { label: '工作区2', value: '2' },
// ... 根据实际需求添加更多选项 // ... 根据实际需求添加更多选项
] as const; ];
// 统一错误处理 // 统一错误处理
const handleApiRequest = async ( const handleApiRequest = async (
@@ -83,34 +85,40 @@ const handleDelete = async (tourismFile: DEVICE.Wayline) => {
); );
}; };
const handleImport = async (file: RcFile) => { const calculateFileMD5 = (file: File): Promise<string> => {
return handleApiRequest( return new Promise((resolve, reject) => {
async () => { const reader = new FileReader();
const formData = new FormData(); const spark = new SparkMD5.ArrayBuffer();
formData.append('file', file);
return await importImage(formData); reader.onload = (e) => {
}, if (e.target?.result) {
'正在上传', spark.append(e.target.result as ArrayBuffer);
'上传素材成功' const md5 = spark.end();
); resolve(md5);
} else {
reject(new Error('Failed to read file'));
}
};
reader.onerror = (error) => reject(error);
reader.readAsArrayBuffer(file);
});
}; };
// 渲染函数 const checkSignExists = async (sign: string) => {
const renderStatus = (status: {} | null | undefined) => { const response = await fetch(`/api/wayline/check-sign?sign=${sign}`);
const statusInfo = statusColorMap[status] || { color: 'gray', text: '未知状态' }; return response.json();
return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
};
const renderType = (type: {} | null | undefined) => {
const typeInfo = typeColorMap[type] || { color: 'gray', text: '未知状态' };
return <Tag color={typeInfo.color}>{typeInfo.text}</Tag>;
}; };
interface FileResponse { interface FileResponse {
id: string; id: string;
name: string; name: string;
url: string; url: string;
// ... 其他字段 sign?: string;
}
interface ExtendedWayline extends DEVICE.Wayline {
fileUrl?: string;
} }
const TableList: React.FC = () => { const TableList: React.FC = () => {
@@ -118,48 +126,82 @@ const TableList: React.FC = () => {
const [params, setParams] = useState<Record<string, string | number>>({}); const [params, setParams] = useState<Record<string, string | number>>({});
const [createModalVisible, handleModalVisible] = useState<boolean>(false); const [createModalVisible, handleModalVisible] = useState<boolean>(false);
const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false); const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
const [currentRow, setCurrentRow] = useState<DEVICE.Wayline>(); const [currentRow, setCurrentRow] = useState<ExtendedWayline>();
const [fileInfo, setFileInfo] = useState<FileResponse>(); const [fileInfo, setFileInfo] = useState<FileResponse>();
const formRef = useRef(); const formRef = useRef<any>();
const handleFileUpload = async (file: RcFile) => { const handleFileUpload = async (file: RcFile) => {
const hide = message.loading('正在上传文件...');
try { try {
const sign = await calculateFileMD5(file);
console.log('文件签名:', sign);
const formData = new FormData(); const formData = new FormData();
formData.append('file', file); formData.append('file', file);
formData.append('sign', sign);
const result = await importImage(formData); const result = await importImage(formData);
if (result) { console.log('上传接口返回结果:', result);
setFileInfo(result);
formRef.current?.setFieldsValue({ if (!result || !result.id) {
waylineId: result.id, hide();
name: result.name message.error('上传失败:未获取到文件信息');
}); return false;
message.success('文件上传成功');
} }
const fileResponse: FileResponse = {
id: result.id,
name: result.name || file.name,
url: result.url || '',
sign: sign
};
setFileInfo(fileResponse);
formRef.current?.setFieldsValue({
waylineId: fileResponse.id,
name: fileResponse.name,
sign: fileResponse.sign
});
hide();
message.success('文件上传成功');
return false; return false;
} catch (error) { } catch (error: any) {
message.error('文件上传失败'); hide();
console.error('文件上传错误:', error);
message.error('文件上传失败:' + (error?.message || '未知错误'));
return false; return false;
} }
}; };
const handleTableAction = useCallback(async ( const handleTableAction = useCallback(async (
action: 'add' | 'edit' | 'delete', action: 'add' | 'edit' | 'delete',
record?: DEVICE.Wayline, record?: ExtendedWayline,
values?: Partial<DEVICE.Wayline> values?: Partial<DEVICE.Wayline>
) => { ): Promise<boolean> => {
let success = false; let success = false;
switch (action) { switch (action) {
case 'add': case 'add':
if (!fileInfo) { if (!fileInfo) {
message.error('请上传航线文件'); message.error('请上传航线文件');
return; return false;
} }
success = await handleAdd({ if (!fileInfo.sign) {
...values, message.error('文件签名获取失败');
fileUrl: fileInfo.url, return false;
}
const waylineData: Omit<DEVICE.Wayline, 'id' | 'createTime' | 'tenantId' | 'updateTime'> = {
waylineId: fileInfo.id, waylineId: fileInfo.id,
name: values.name || fileInfo.name name: values?.name || fileInfo.name,
} as DEVICE.Wayline); sign: fileInfo.sign,
droneModelKey: values?.droneModelKey || '',
payloadModelKeys: values?.payloadModelKeys || '',
workspaceId: values?.workspaceId || '',
favorited: (values?.favorited?.toString() || '0') as string,
templateTypes: values?.templateTypes || '',
userName: values?.userName || ''
};
success = await handleAdd(waylineData as DEVICE.Wayline);
if (success) { if (success) {
handleModalVisible(false); handleModalVisible(false);
setFileInfo(undefined); setFileInfo(undefined);
@@ -171,7 +213,8 @@ const TableList: React.FC = () => {
...values, ...values,
...(fileInfo ? { ...(fileInfo ? {
fileUrl: fileInfo.url, fileUrl: fileInfo.url,
waylineId: fileInfo.id waylineId: fileInfo.id,
sign: fileInfo.sign
} : {}) } : {})
}; };
success = await handleEdit(record, updateData); success = await handleEdit(record, updateData);
@@ -183,15 +226,18 @@ const TableList: React.FC = () => {
} }
break; break;
case 'delete': case 'delete':
success = await handleDelete(record!); if (record) {
success = await handleDelete(record);
}
break; break;
} }
if (success && actionRef.current) { if (success && actionRef.current) {
actionRef.current.reload(); actionRef.current.reload();
} }
return success;
}, [fileInfo]); }, [fileInfo]);
const columns: ProColumns<DEVICE.Wayline>[] = [ const columns: ProColumns<ExtendedWayline>[] = [
{ {
dataIndex: 'index', dataIndex: 'index',
valueType: 'indexBorder', valueType: 'indexBorder',
@@ -216,14 +262,14 @@ const TableList: React.FC = () => {
{ {
title: '航线文件', title: '航线文件',
dataIndex: 'fileUrl', dataIndex: 'fileUrl',
render: (fileUrl, record) => fileUrl ? ( render: (_, record) => record.fileUrl ? (
<a <a
href={fileUrl} href={record.fileUrl}
download={record.name} download={record.name}
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();
const link = document.createElement('a'); const link = document.createElement('a');
link.href = fileUrl; link.href = record.fileUrl || '';
link.download = record.name || 'wayline.kmz'; link.download = record.name || 'wayline.kmz';
document.body.appendChild(link); document.body.appendChild(link);
link.click(); link.click();
@@ -234,6 +280,12 @@ const TableList: React.FC = () => {
</a> </a>
) : '-' ) : '-'
}, },
{
title: '文件签名',
dataIndex: 'sign',
copyable: true,
ellipsis: true,
},
{ {
title: '操作', title: '操作',
key: 'action', key: 'action',
@@ -275,7 +327,7 @@ const TableList: React.FC = () => {
> >
<ProFormText name="name" label="搜索" placeholder="输入关键字" /> <ProFormText name="name" label="搜索" placeholder="输入关键字" />
</QueryFilter> </QueryFilter>
<ProTable<DEVICE.Wayline> <ProTable<ExtendedWayline>
rowKey="id" rowKey="id"
headerTitle="航线列表" headerTitle="航线列表"
request={wayline} request={wayline}
@@ -343,6 +395,10 @@ const TableList: React.FC = () => {
hidden hidden
name="waylineId" name="waylineId"
/> />
<ProFormText
hidden
name="sign"
/>
</ProForm.Group> </ProForm.Group>
<ProForm.Group> <ProForm.Group>
@@ -359,15 +415,22 @@ const TableList: React.FC = () => {
</Button> </Button>
</Upload> </Upload>
{fileInfo && ( {fileInfo && (
<div style={{ marginTop: 8, color: '#52c41a' }}> <div style={{ marginTop: 8 }}>
已上传:{fileInfo.name} <div style={{ color: '#52c41a' }}>
已上传:{fileInfo.name}
</div>
<div style={{ color: '#666', fontSize: '12px' }}>
文件签名:{fileInfo.sign}
</div>
</div> </div>
)} )}
</div> </div>
</ProForm.Group> </ProForm.Group>
</ModalForm> </ModalForm>
<UpdateForm <UpdateForm
onSubmit={(values) => handleTableAction('edit', currentRow, values)} onSubmit={async (values) => {
await handleTableAction('edit', currentRow, values);
}}
onVisibleChange={(visible) => { onVisibleChange={(visible) => {
handleUpdateModalVisible(visible); handleUpdateModalVisible(visible);
if (!visible) { if (!visible) {
@@ -1,69 +0,0 @@
import {
ModalForm,
ProForm,
ProFormText,
} from '@ant-design/pro-components';
import { Form } from 'antd';
export type FormValueType = Partial<ORDERS.Tourism>;
export type UpdateFormProps = {
onVisibleChange: (flag: boolean) => void;
onSubmit: (values: FormValueType) => Promise<void>;
updateModalVisible: boolean;
values?: ORDERS.Tourism;
};
const UpdateForm: React.FC<UpdateFormProps> = (props) => {
const [form] = Form.useForm();
return (
<ModalForm
title="修改二维码"
form={form}
visible={props.updateModalVisible}
onFinish={props.onSubmit}
onVisibleChange={props.onVisibleChange}
>
<ProForm.Group>
<ProFormText
rules={[
{
required: true,
message: '名称不为空',
},
]}
width="md"
name="tourismName"
label="名称"
placeholder="输入名称"
/>
<ProFormText
rules={[
{
required: true,
message: '地址不为空',
},
]}
width="md"
name="tourismAddress"
label="地址"
placeholder="输入地址"
/>
<ProFormText
rules={[
{
required: true,
message: '手机号不为空',
},
]}
width="md"
name="tourismPhone"
label="手机号"
placeholder="输入手机号"
/>
</ProForm.Group>
</ModalForm>
);
};
export default UpdateForm;
@@ -1 +0,0 @@
@import (reference) '~antd/es/style/themes/index';
@@ -1,293 +0,0 @@
import { deleteQrcode, qrcode, saveOrUpdateQrcode } from '@/services/orders/api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
ModalForm,
PageContainer,
ProForm,
ProFormSelect,
ProFormText,
ProTable,
QueryFilter,
} from '@ant-design/pro-components';
import { Typography, Popconfirm, Space, message, Image, Button, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import UpdateForm from './components/UpdateForm';
const { Link } = Typography;
const handleAdd = async (fields: ORDERS.Qrcode) => {
const hide = message.loading('正在添加');
try {
const result = await saveOrUpdateQrcode({ ...fields });
hide();
if (result.resp_code === 0) {
message.success('添加成功');
return true;
} else {
message.error(result.resp_msg);
return false;
}
} catch (error) {
hide();
message.error('添加失败');
return false;
}
};
const handleEdit = async (fields: ORDERS.Qrcode) => {
const hide = message.loading('正在更新');
try {
const result = await saveOrUpdateQrcode({ ...fields });
hide();
if (result.resp_code === 0) {
message.success('修改成功');
return true;
} else {
message.error(result.resp_msg);
return false;
}
} catch (error) {
hide();
message.error('修改失败');
return false;
}
};
const handleDelete = async (qrcode: ORDERS.Qrcode) => {
const hide = message.loading('正在删除');
try {
const result = await deleteQrcode(qrcode.id);
hide();
if (result.resp_code === 0) {
message.success('删除成功');
return true;
} else {
message.error(result.resp_msg);
return false;
}
} catch (error) {
hide();
message.error('删除失败');
return false;
}
};
// 状态颜色映射
const statusColorMap = {
0: { color: 'green', text: '启用' },
1: { color: 'red', text: '未启用' },
};
// 渲染状态标签
const renderStatus = (status: {} | null | undefined) => {
const statusInfo = statusColorMap[status] || { color: 'gray', text: '未知状态' };
return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
};
const TableList: React.FC = () => {
const actionRef = useRef<ActionType>();
const [params, setParams] = useState<Record<string, string | number>>({ });
const [createModalVisible, handleModalVisible] = useState<boolean>(false);
const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
const [currentRow, setCurrentRow] = useState<ORDERS.Qrcode>();
const columns: ProColumns<ORDERS.Qrcode>[] = [
{
dataIndex: 'index',
valueType: 'indexBorder',
},
{
title: 'ID',
dataIndex: 'id',
},
{
title: 'CodeID',
dataIndex: 'codeId',
},
{
title: '景区ID',
dataIndex: 'tourismId',
},
{
title: '文件',
dataIndex: 'viewUrl',
render: (viewUrl) => <Image src={viewUrl} width={100} />
},
{
title: '价格',
dataIndex: 'price',
},
{
title: '设备SN',
dataIndex: 'deviceSn',
},
{
title: '状态',
dataIndex: 'status',
render: (status) => renderStatus(status),
},
{
title: '创建时间',
dataIndex: 'createTime',
valueType: 'dateTime',
},
{
title: '操作',
key: 'action',
render: (_, entity) =>
<Space>
<Link
onClick={() => {
setCurrentRow(entity);
handleUpdateModalVisible(true);
}}
>
修改
</Link>
<Popconfirm
title={`确认删除景区[${entity.codeId}]?`}
onConfirm={async () => {
const success = await handleDelete(entity);
if (success) {
if (actionRef.current) {
actionRef.current.reload();
}
}
}}
>
<Link>删除</Link>
</Popconfirm>
</Space>
},
];
return (
<PageContainer header={{ subTitle: '管理任务' }}>
<QueryFilter
defaultCollapsed
split
span={6}
className="query-filter"
onFinish={async (values) => setParams(values)}
>
<ProFormText name="name" label="搜索" placeholder="输入关键字" />
</QueryFilter>
<ProTable<ORDERS.Qrcode>
rowKey="id"
headerTitle="二维码列表"
request={qrcode}
actionRef={actionRef}
columns={columns}
search={false}
params={params}
pagination={{
showSizeChanger: true,
showQuickJumper: true,
}}
toolBarRender={() => [
<>
<Button
type="primary"
onClick={() => {
handleModalVisible(true);
}}
>
<PlusOutlined /> 添加
</Button>
</>,
]}
/>
<ModalForm
title="添加二维码"
// layout="horizontal"
visible={createModalVisible}
onVisibleChange={handleModalVisible}
modalProps={{ destroyOnClose: true }}
onFinish={async (values) => {
const success = await handleAdd(values);
if (success) {
handleModalVisible(false);
if (actionRef.current) {
actionRef.current.reload();
}
}
}}
>
<ProForm.Group>
<ProFormSelect
rules={[
{
required: true,
message: '景区不为空',
},
]}
width="md"
name="tourismId"
label="景区"
placeholder="请选择景区"
options={[
{ label: '北塘古镇', value: 33 },
{ label: '海丝首港', value: 32 },
{ label: '武汉东湖牡丹园', value: 35 },
{ label: '武汉东湖樱花园', value: 36 },
// 添加更多选项...
]}
/>
<ProFormText
rules={[
{
required: true,
message: '价格不为空',
},
]}
width="md"
name="price"
label="景点打卡价格"
placeholder="输入价格(单位:分)"
/>
<ProFormSelect
rules={[
{
required: true,
message: '设备不为空',
},
]}
width="md"
name="deviceSn"
label="设备编号"
placeholder="输入设备编号"
options={[
{ label: '7CTDM6F00B744S', value: '7CTDM6F00B744S' },
{ label: '8UUXN2A00A00LR', value: '8UUXN2A00A00LR' },
{ label: '5YSZMBS0030BJ8', value: '5YSZMBS0030BJ8' },
// 添加更多选项...
]}
/>
</ProForm.Group>
</ModalForm>
<UpdateForm
onSubmit={async (values) => {
if (currentRow) {
const success = await handleEdit({ ...currentRow, ...values });
if (success) {
handleUpdateModalVisible(false);
if (actionRef.current) {
actionRef.current.reload();
}
}
setCurrentRow(undefined);
}
}}
onVisibleChange={handleUpdateModalVisible}
updateModalVisible={updateModalVisible}
values={currentRow}
/>
</PageContainer>
);
};
export default TableList;
@@ -32,10 +32,18 @@ const TYPE_COLORS = {
}; };
// 获取文件类型标签颜色 // 获取文件类型标签颜色
const getTypeColor = (fileType: string) => { const getTypeColor = (fileType: string | null) => {
if (!fileType) return TYPE_COLORS.default;
return TYPE_COLORS[fileType] || TYPE_COLORS.default; return TYPE_COLORS[fileType] || TYPE_COLORS.default;
}; };
// 获取文件类型显示文本
const getFileTypeDisplay = (fileType: string | null) => {
if (!fileType) return 'UNKNOWN';
const parts = fileType.split('/');
return parts.length > 1 ? parts[1].toUpperCase() : fileType.toUpperCase();
};
// 处理文件删除 // 处理文件删除
const handleDelete = async (file: ORDERS.OrderFile) => { const handleDelete = async (file: ORDERS.OrderFile) => {
const hide = message.loading('正在删除文件...'); const hide = message.loading('正在删除文件...');
@@ -77,7 +85,7 @@ const TableList: React.FC = () => {
width: 200, width: 200,
render: (viewUrl, record) => ( render: (viewUrl, record) => (
<Space direction="vertical"> <Space direction="vertical">
{FILE_CONFIG.imageTypes.includes(record.fileType) ? ( {record.fileType && FILE_CONFIG.imageTypes.includes(record.fileType) ? (
<Image <Image
src={viewUrl as string} src={viewUrl as string}
width={100} width={100}
@@ -85,7 +93,7 @@ const TableList: React.FC = () => {
/> />
) : ( ) : (
<Tag color={getTypeColor(record.fileType)}> <Tag color={getTypeColor(record.fileType)}>
{record.fileType.split('/')[1].toUpperCase()} {getFileTypeDisplay(record.fileType)}
</Tag> </Tag>
)} )}
<Space> <Space>
@@ -104,8 +112,8 @@ const TableList: React.FC = () => {
dataIndex: 'fileType', dataIndex: 'fileType',
width: 120, width: 120,
render: (type) => ( render: (type) => (
<Tag color={getTypeColor(type as string)}> <Tag color={getTypeColor(type as string | null)}>
{(type as string).split('/')[1].toUpperCase()} {getFileTypeDisplay(type as string | null)}
</Tag> </Tag>
), ),
}, },
@@ -28,5 +28,68 @@ export async function deleteWayline(id: number) {
return result; return result;
} }
// 获取设备列表
export async function device(params?: { [key: string]: any }) {
const { current, pageSize, ...rest } = params ?? {};
try {
const result = await request<API.Result<DEVICE.Device[]>>('/api-device/device', {
method: 'GET',
params: {
page: current,
limit: pageSize,
...rest,
},
});
// 根据实际返回的数据结构进行处理
return {
data: result.data || [], // 直接使用返回的数组
success: result.resp_code === 0,
total: result.count || 0, // 使用返回的count作为总数
};
} catch (error) {
console.error('获取设备列表失败:', error);
return {
data: [],
success: false,
total: 0,
};
}
}
// 新增或更新设备
export async function saveOrUpdateDevice(data: Partial<DEVICE.Device>): Promise<API.Result<DEVICE.Device>> {
return request('/api-device/device', {
method: 'POST',
data: {
...data,
createTime: data.createTime || Date.now(),
updateTime: Date.now(),
},
});
}
// 删除设备
export async function deleteDevice(deviceSn: string) {
return request<API.Result<void>>(`/api-device/device/${deviceSn}`, {
method: 'DELETE',
});
}
// 获取设备详情
export async function getDevice(deviceSn: string) {
return request<API.Result<DEVICE.Device>>(`/api-device/device/${deviceSn}`, {
method: 'GET',
});
}
// 更新设备绑定状态
export async function updateDeviceBoundStatus(deviceSn: string, boundStatus: DEVICE.BoundStatus) {
return request<API.Result<void>>(`/api-device/device/${deviceSn}/bound-status`, {
method: 'PUT',
data: { boundStatus },
});
}
@@ -18,5 +18,49 @@ declare namespace DEVICE {
tenantId?: string; tenantId?: string;
updateTime?: string; updateTime?: string;
} }
type Device = {
id?: number;
deviceSn: string; // 设备序列号
deviceName: string; // 设备型号名称
userId?: string; // 绑定账号
nickname: string; // 设备自定义名称
workspaceId?: string; // 所属工作区
deviceType: number; // 设备类型
subType: number; // 设备子类型
domain: number; // 设备域
firmwareVersion?: string; // 固件版本
compatibleStatus: 0 | 1; // 固件版本一致性状态
version?: string; // 协议版本
deviceIndex?: string; // 设备索引(A控/B控)
childSn?: string; // 网关控制的设备
createTime?: number; // 创建时间
updateTime?: number; // 更新时间
boundTime?: number; // 绑定时间
boundStatus: 0 | 1; // 绑定状态
loginTime?: number; // 最后登录时间
deviceDesc?: string; // 设备描述
urlNormal?: string; // 设备图标
urlSelect?: string; // 设备选中图标
tenantId?: string; // 租户ID
}
// 设备类型枚举
enum DeviceType {
DOCK = 1,
DRONE = 2,
REMOTE_CONTROL = 3,
}
// 设备绑定状态
enum BoundStatus {
UNBOUND = 0,
BOUND = 1,
}
// 固件兼容状态
enum CompatibleStatus {
INCONSISTENT = 0,
CONSISTENT = 1,
}
} }